from rest_framework import serializers
#from rest_framework_mongoengine.serializers import DocumentSerializer
from rest_framework.validators import UniqueValidator
#from rest_framework.validators import UniqueTogetherValidator
from decimal import Decimal
import bleach
from .models import *
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# Disable SSL certificate verification warnings
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

from collections import OrderedDict
from bson import ObjectId
from datetime import datetime

class OrderedDictField(serializers.Field):
    def to_representation(self, value):
        if isinstance(value, OrderedDict):
            # Recursively process the OrderedDict to handle ObjectIds and datetime objects
            return {k: str(v) if isinstance(v, ObjectId) else v.isoformat() if isinstance(v, datetime) else self.to_representation(v) for k, v in value.items()}
        elif isinstance(value, list):
            # Process the list items to handle ObjectIds and datetime objects
            return [self.to_representation(v) for v in value]
        elif isinstance(value, ObjectId):
            # Convert ObjectId to string
            return str(value)
        elif isinstance(value, datetime):
            # Convert datetime to ISO 8601 string format
            return value.isoformat()
        return value

    def to_internal_value(self, data):
        return data


class OfficeSerializer(serializers.ModelSerializer):
    id = serializers.CharField(read_only = True)
    office_id = serializers.IntegerField(read_only = True, min_value=1)
    name = serializers.CharField(read_only = True, max_length=100)
    email = serializers.EmailField(max_length=100, allow_blank=False)
    address = serializers.CharField(read_only = True, max_length=255)
    street_number = serializers.CharField(read_only = True, max_length=255)
    complement = serializers.CharField(read_only = True, max_length=255)
    postal_code = serializers.CharField(read_only = True, max_length=20)
    website = serializers.URLField(read_only = True, max_length=100, min_length=None, allow_blank=False)
    #logo = serializers.SerializerMethodField()
    logo = serializers.URLField(read_only = True, max_length=255, min_length=None, allow_blank=False)
    telephone = serializers.CharField(read_only = True, max_length=50)
    lat = serializers.FloatField(read_only = True)
    lng = serializers.FloatField(read_only = True)
    total_properties = serializers.IntegerField(read_only = True)
    creci = serializers.CharField(read_only = True, max_length=20)
    neighborhood = serializers.CharField(read_only = True, max_length=100)
    region_name = serializers.CharField(read_only = True, max_length=100)
    city = serializers.CharField(read_only = True, max_length=100)
    state = serializers.CharField(read_only = True, max_length=100)
    state_abbreviation = serializers.CharField(read_only = True, max_length=10)
    country = serializers.CharField(read_only = True, max_length=100)
    country_abbreviation = serializers.CharField(read_only = True, max_length=10)
    complements_info = OrderedDictField()
    
    banners = serializers.SerializerMethodField()
    
    def get_banners(self, obj):
        try:
            # Get the related AgenciaBanner objects for the current Office
            from panel.models import AgenciaBanner
            # banners = AgenciaBanner.objects.using('mongodb').get(agencia_id=obj.office_id)
            agencia_id = int(obj.office_id)
            banners_queryset = AgenciaBanner.objects.filter(agencia_id=agencia_id)
            # Extract the banner data from the related AgenciaBanner
            banners_data = []
            for banner in banners_queryset:
                banner_data = {
                    'banner_id': str(banner.id),
                    'banner_order': banner.ordem,
                    'banner_description': banner.descricao,
                    'banners_image': banner.imagem,
                    'banner_link': banner.link,
                    'banner_new_window': banner.nova_janela,
                    'banner_status': banner.status,
                    'banner_created_at': banner.created_at.strftime('%Y-%m-%dT%H:%M:%S') if banner.created_at else None,
                    'banner_updated_at': banner.updated_at.strftime('%Y-%m-%dT%H:%M:%S') if banner.updated_at else None,
                }
                banners_data.append(banner_data)
            import json
            banners_data = json.loads(json.dumps(banners_data, default=str))
            return banners_data
        except Exception as e:
            print(e)
            return None
    

    #lat = serializers.CharField(read_only = True, max_length=20)
    #lng = serializers.CharField(read_only = True, max_length=20)
    #distance = serializers.CharField(read_only = True, max_length=20)
    #distance = serializers.DecimalField(read_only = True, max_digits=20, decimal_places=10)

    #distance = serializers.FloatField(read_only = True)


    # def get_logo(self, instance):
    #     logo_instance = instance.logo
    #     image_formats = ("image/png", "image/jpeg", "image/jpg", "image/gif")
        
    #     try:
    #         response = requests.head(logo_instance, verify=False)
    #         if response.status_code == 200 and response.headers["content-type"] in image_formats:
    #             return logo_instance
    #     except Exception as e:
    #         pass  # Image doesn't exist or couldn't be accessed
    #     return None


    
    def validate(self, attrs):
        attrs['name'] = bleach.clean(attrs['name'])
        attrs['telephone'] = bleach.clean(attrs['telephone'])
        attrs['country'] = bleach.clean(attrs['country'])
        attrs['country_abbreviation'] = bleach.clean(attrs['country_abbreviation'])
        attrs['state'] = bleach.clean(attrs['state'])
        attrs['state_abbreviation'] = bleach.clean(attrs['state_abbreviation'])
        attrs['city'] = bleach.clean(attrs['city'])
        attrs['neighborhood'] = bleach.clean(attrs['neighborhood'])
        attrs['complement'] = bleach.clean(attrs['complement'])
        attrs['address'] = bleach.clean(attrs['address'])
        attrs['street_number'] = bleach.clean(attrs['street_number'])
        attrs['postal_code'] = bleach.clean(attrs['postal_code'])
        return super().validate(attrs)
    
    def validate_office_id(self, value):
        if (value < 1):
            raise serializers.ValidationError('Office ID must be equal or higher than 1!')
        return value
      
    class Meta:
        model = Offices
        fields = '__all__'


class AgentSerializer(serializers.ModelSerializer):
    id = serializers.CharField(read_only = True)
    agent_id = serializers.IntegerField(read_only = True, min_value=1, validators=[UniqueValidator(queryset=Agents.objects.using('mongodb').all())])
    name = serializers.CharField(read_only = True, max_length=100)
    email = serializers.EmailField(max_length=100, allow_blank=False)
    telephone = serializers.CharField(read_only = True, max_length=50)
    creci = serializers.CharField(read_only = True, max_length=20)
    website = serializers.URLField(read_only = True, max_length=100, min_length=None, allow_blank=False)
    region_id = serializers.IntegerField(read_only = True)
    profile_picture = serializers.CharField(read_only = True, max_length=255)
    #profile_picture = serializers.SerializerMethodField()
    total_properties = serializers.IntegerField(read_only = True)
    address = serializers.CharField(read_only = True, max_length=255)
    street_number = serializers.CharField(read_only = True, max_length=255)
    complement = serializers.CharField(read_only = True, max_length=255)
    postal_code = serializers.CharField(read_only = True, max_length=20)
    neighborhood = serializers.CharField(read_only = True, max_length=100)
    region_name = serializers.CharField(read_only = True, max_length=100)
    city = serializers.CharField(read_only = True, max_length=100)
    state = serializers.CharField(read_only = True, max_length=100)
    state_abbreviation = serializers.CharField(read_only = True, max_length=10)
    country = serializers.CharField(read_only = True, max_length=100)
    country_abbreviation = serializers.CharField(read_only = True, max_length=10)
    lng = serializers.FloatField(read_only = True)
    lat = serializers.FloatField(read_only = True)
    # distance = models.DecimalField(null=True, max_digits=20, decimal_places=10, default=None)
    #distance = serializers.DecimalField(read_only = True, max_digits=20, decimal_places=10)
    #distance = serializers.CharField(read_only = True, max_length=20)
    #distance = serializers.FloatField(read_only = True)
    office = OfficeSerializer(read_only=True)
    has_profile_picture = serializers.SerializerMethodField()
    has_creci = serializers.SerializerMethodField()
    complements_info = OrderedDictField()

       

    
    
    # def get_profile_picture(self, instance):
    #     profile_picture_instance = instance.profile_picture
    #     print(f"Profile picture: {profile_picture_instance}")
    #     image_formats = ("image/png", "image/jpeg", "image/jpg", "image/gif")
        
    #     try:
    #         response = requests.head(profile_picture_instance, verify=False)
    #         if response.status_code == 200 and response.headers["content-type"] in image_formats:
    #             return profile_picture_instance
    #     except Exception as e:
    #         pass  # Image doesn't exist or couldn't be accessed
    #     return None

    # def get_has_profile_picture(self, instance):
    #     if self.get_profile_picture(instance) == instance.profile_picture:
    #         return 1
    #     return 0
    
    def get_has_profile_picture(self, instance):
        if instance.profile_picture:
            return 1
        return 0
    
    def get_has_creci(self, instance):
        if instance.creci:
            return 1
        return 0
        

    def validate(self, attrs):
        attrs['name'] = bleach.clean(attrs['name'])
        return super().validate(attrs)
    
    def validate_agent_id(self, value):
        if (value < 1):
            raise serializers.ValidationError('Agent ID must be equal or higher than 1!')
        return value
      
    class Meta:
        model = Agents
        ordering = '__all__'
        fields = '__all__'
        
        
class FeatureSerializer(serializers.ModelSerializer):
    
    id = serializers.CharField(read_only = True)
    feature_id = serializers.IntegerField(read_only = True, min_value=1, validators=[UniqueValidator(queryset=Features.objects.using('mongodb').all())])
    feature_name_en = serializers.CharField(read_only = True, max_length=100)
    feature_name_pt = serializers.CharField(read_only = True, max_length=100)
    #properties = serializers.SlugRelatedField(read_only=True, many=True, slug_field='property_id')

    def validate(self, attrs):
        attrs['feature_name_en'] = bleach.clean(attrs['feature_name_en'])
        attrs['feature_name_pt'] = bleach.clean(attrs['feature_name_pt'])
        return super().validate(attrs)
    
    def validate_feature_id(self, value):
        if (value < 1):
            raise serializers.ValidationError('Feature ID must be equal or higher than 1!')
        return value
    

      
    class Meta:
        model = Features
        fields = '__all__'
        
        
        
        
class UsageSerializer(serializers.ModelSerializer):
    
    id = serializers.CharField(read_only = True)
    usage_id = serializers.IntegerField(read_only = True, min_value=1, validators=[UniqueValidator(queryset=Usages.objects.using('mongodb').all())])
    usage_name_en = serializers.CharField(read_only = True, max_length=100)
    usage_name_pt = serializers.CharField(read_only = True, max_length=100)

    def validate(self, attrs):
        attrs['usage_name_en'] = bleach.clean(attrs['usage_name_en'])
        attrs['usage_name_pt'] = bleach.clean(attrs['usage_name_pt'])
        return super().validate(attrs)
    
    def validate_feature_id(self, value):
        if (value < 1):
            raise serializers.ValidationError('Usage ID must be equal or higher than 1!')
        return value
      
    class Meta:
        model = Usages
        fields = '__all__'
        

class TypeSerializer(serializers.ModelSerializer):
    
    id = serializers.CharField(read_only = True)
    type_id = serializers.IntegerField(read_only = True, min_value=1, validators=[UniqueValidator(queryset=Types.objects.using('mongodb').all())])
    type_name_en = serializers.CharField(read_only = True, max_length=100)
    type_name_pt = serializers.CharField(read_only = True, max_length=100)
    usage = UsageSerializer(read_only=True)

    def validate(self, attrs):
        attrs['type_name_en'] = bleach.clean(attrs['type_name_en'])
        attrs['type_name_pt'] = bleach.clean(attrs['type_name_pt'])
        return super().validate(attrs)
    
    def validate_type_id(self, value):
        if (value < 1):
            raise serializers.ValidationError('Type ID must be equal or higher than 1!')
        return value
      
    class Meta:
        model = Types
        fields = '__all__'



class LocationSerializer(serializers.ModelSerializer):
    
    id = serializers.CharField(read_only = True)
    property_location_id = serializers.IntegerField(read_only = True, min_value=1, 
                                                 validators=[UniqueValidator(queryset=Location.objects.using('mongodb').all())])
    display_address = serializers.CharField(read_only = True, max_length=20)
    country = serializers.CharField(read_only = True, max_length=100)
    country_abbreviation = serializers.CharField(read_only = True, max_length=10)
    state = serializers.CharField(read_only = True, max_length=100)
    city = serializers.CharField(read_only = True, max_length=100)
    zone = serializers.CharField(read_only = True, max_length=100)
    neighborhood = serializers.CharField(read_only = True, max_length=100)
    complement = serializers.CharField(read_only = True, max_length=255)
    address = serializers.CharField(read_only = True, max_length=255)
    street_number = serializers.CharField(read_only = True, max_length=255)
    postal_code = serializers.CharField(read_only = True, max_length=20)
    #lat = serializers.CharField(read_only = True, max_length=20)
    #lng = serializers.CharField(read_only = True, max_length=20)
    lat = serializers.FloatField(read_only = True)
    lng = serializers.FloatField(read_only = True)
    

    def validate(self, attrs):
        attrs['display_address'] = bleach.clean(attrs['display_address'])
        attrs['country'] = bleach.clean(attrs['country'])
        attrs['country_abbreviation'] = bleach.clean(attrs['abbreviation'])
        attrs['state'] = bleach.clean(attrs['state'])
        attrs['city'] = bleach.clean(attrs['city'])
        attrs['zone'] = bleach.clean(attrs['zone'])
        attrs['neighborhood'] = bleach.clean(attrs['neighborhood'])
        attrs['complement'] = bleach.clean(attrs['complement'])
        attrs['address'] = bleach.clean(attrs['address'])
        attrs['street_number'] = bleach.clean(attrs['street_number'])
        attrs['postal_code'] = bleach.clean(attrs['postal_code'])
        attrs['lat'] = bleach.clean(attrs['lat'])
        attrs['lng'] = bleach.clean(attrs['lng'])
        return super().validate(attrs)
    
    def validate_property_location_id(self, value):
        if (value < 1):
            raise serializers.ValidationError('Property Location ID must be equal or higher than 1!')
        return value
      
    class Meta:
        model = Location
        fields = '__all__'


class PropertySerializer(serializers.ModelSerializer):
    
    id = serializers.CharField(read_only = True)
    property_id = serializers.IntegerField(read_only = True, min_value=1, validators=[UniqueValidator(queryset=Properties.objects.using('mongodb').all())])
    listing_id = serializers.CharField(read_only = True, max_length=100)
    title = serializers.CharField(read_only = True, max_length=255)
    transaction_type = serializers.CharField(read_only = True, max_length=50)
    detail_view_url = serializers.URLField(read_only = True, max_length=100, min_length=None, allow_blank=False)
    description = serializers.CharField(read_only=True)
    list_price = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    list_price_currency = serializers.CharField(read_only = True, max_length=5)  
    rental_price = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    rental_price_currency = serializers.CharField(read_only = True, max_length=5)
    rental_price_period = serializers.CharField(read_only = True, max_length=50)
    property_administration_fee = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    property_administration_fee_period = serializers.CharField(read_only = True, max_length=30)
    yearly_tax = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    yearly_tax_currency = serializers.CharField(read_only = True, max_length=5)
    living_area = serializers.IntegerField(read_only = True)
    living_area_unit = serializers.CharField(read_only = True, max_length=30)
    year_built = serializers.IntegerField(read_only = True, min_value=4, max_value=4)
    bedrooms = serializers.IntegerField(read_only = True)
    bathrooms = serializers.IntegerField(read_only = True)
    garage = serializers.IntegerField(read_only = True)
    garage_type = serializers.CharField(read_only = True, max_length=30)
    unit_floor = serializers.IntegerField(read_only = True)
    unit_number = serializers.CharField(read_only = True, max_length=30)
    publish_date = serializers.DateTimeField(read_only=True, default=None)
    sync_date = serializers.DateTimeField(read_only=True, default=None)
    region_id = serializers.IntegerField(read_only = True)
    type = serializers.SerializerMethodField()
    usage = serializers.SerializerMethodField()
    office = serializers.SerializerMethodField()
    agent = serializers.SerializerMethodField()
    location = serializers.SerializerMethodField()
    features = serializers.SerializerMethodField()
    medias = serializers.SerializerMethodField()
    
    def get_usage(self, obj):
        try:
            # Get the related Usage objects for the current property
            property_usage = Usages.objects.using('mongodb').get(usage_id=obj.usage_id)
            # Extract the media data from the related PropertiesMedia
            usage_data = {
                    'usage_id': property_usage.usage_id,
                    'usage_name_en': property_usage.usage_name_en,
                    'usage_name_pt': property_usage.usage_name_pt,
                    # Add other media fields as needed
                }
            return usage_data
        except:
            return None
    
    def get_type(self, obj):
        try:
            # Get the related Type objects for the current property
            property_type = Types.objects.using('mongodb').get(type_id=obj.type_id)
            # Extract the media data from the related PropertiesMedia
            type_data = {
                    'type_id': property_type.type_id,
                    'type_name_en': property_type.type_name_en,
                    'type_name_pt': property_type.type_name_pt,
                    # Add other media fields as needed
                }
            return type_data
        except:
            return None
    
    def get_office(self, obj):
        try:
            # Get the related PropertiesFeatures objects for the current property
            property_office = Offices.objects.using('mongodb').get(office_id=obj.office_id)
            # Extract the feature data from the related PropertiesFeatures
            office_data = {
                    'office_id': property_office.office_id,
                    'name': property_office.name,
                    'website': property_office.website,
                    'logo': property_office.logo,
                    'telephone': property_office.telephone,
                    'country': property_office.country,
                    'country_abbreviation': property_office.country_abbreviation,
                    'state': property_office.state,
                    'state_abbreviation': property_office.state_abbreviation,
                    'city': property_office.city,
                    'zone': property_office.zone,
                    'neighborhood': property_office.neighborhood,
                    'complement': property_office.complement,
                    'address': property_office.address,
                    'street_number': property_office.street_number,
                    'postal_code': property_office.postal_code,
                    'total_properties': property_office.total_properties,
                }
            return office_data
        except:
            return None
    
    def get_agent(self, obj):
        try:
            # Get the related PropertiesFeatures objects for the current property
            property_agent = Agents.objects.using('mongodb').get(agent_id=obj.agent_id)
            # Extract the feature data from the related PropertiesFeatures
            agent_data = {
                    'agent_id': property_agent.agent_id,
                    'name': property_agent.name,
                    'email': property_agent.email,
                    'profile_picture': property_agent.profile_picture,
                    'total_properties': property_agent.total_properties,
                }
            return agent_data
        except:
            return None
    
    def get_location(self, obj):
        try:
            # Get the related PropertiesFeatures objects for the current property
            property_location = Location.objects.using('mongodb').get(property_location_id=obj.location_id)
            # Extract the feature data from the related PropertiesFeatures
            location_data = {
                    'property_location_id': property_location.property_location_id,
                    'display_address': property_location.display_address,
                    'country': property_location.country,
                    'country_abbreviation': property_location.country_abbreviation,
                    'state': property_location.state,
                    'city': property_location.city,
                    'zone': property_location.zone,
                    'neighborhood': property_location.neighborhood,
                    'complement': property_location.complement,
                    'address': property_location.address,
                    'street_number': property_location.street_number,
                    'postal_code': property_location.postal_code,
                    'lat': property_location.lat,
                    'lng': property_location.lng,
                }
            return location_data
        except:
            return None
    

    def get_features(self, obj):
        try:
            # Get the related PropertiesFeatures objects for the current property
            property_features = PropertiesFeatures.objects.using('mongodb').filter(property=obj)
            # Extract the feature data from the related PropertiesFeatures
            feature_data = [
                {
                    'feature_id': pf.feature.feature_id,
                    'feature_name_en': pf.feature.feature_name_en,
                    'feature_name_pt': pf.feature.feature_name_pt,
                    # Add other feature fields if needed
                }
                for pf in property_features
            ]
            return feature_data
        except:
            return None
    
    def get_medias(self, obj):
        try:
            # Get the related PropertiesMedia objects for the current property
            property_medias = PropertiesMedia.objects.using('mongodb').filter(property=obj)[:5]
            # Extract the media data from the related PropertiesMedia
            media_data = [
                {
                    'property_media_id': pm.property_media_id,
                    'type': pm.type,
                    'main': pm.main,
                    'url': pm.url,
                    # Add other media fields as needed
                }
                for pm in property_medias
            ]
            return media_data
        except:
            return None

    
    
    def validate(self, attrs):
        attrs['title'] = bleach.clean(attrs['title'])
        attrs['transaction_type'] = bleach.clean(attrs['transaction_type'])
        attrs['description'] = bleach.clean(attrs['description'])
        attrs['list_price_currency'] = bleach.clean(attrs['list_price_currency'])
        attrs['living_area_unit'] = bleach.clean(attrs['living_area_unit'])
        attrs['garage_type'] = bleach.clean(attrs['garage_type'])
        attrs['unit_number'] = bleach.clean(attrs['unit_number'])

        return super().validate(attrs)
    
    def validate_listing_id(self, value):
        if (value < 1):
            raise serializers.ValidationError('Listing ID must be equal or higher than 1!')
        return value
      
    class Meta:
        model = Properties
        fields = '__all__'
        depth = 2

class PropertyRawSerializer(serializers.ModelSerializer):
    
    property_id = serializers.IntegerField(read_only = True, min_value=1, validators=[UniqueValidator(queryset=Properties.objects.using('mongodb').all())])
    listing_id = serializers.CharField(read_only = True, max_length=100)
    title = serializers.CharField(read_only = True, max_length=255)
    transaction_type = serializers.CharField(read_only = True, max_length=50)
    detail_view_url = serializers.URLField(read_only = True, max_length=100, min_length=None, allow_blank=False)
    description = serializers.CharField(read_only=True)
    list_price = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    list_price_currency = serializers.CharField(read_only = True, max_length=5)  
    rental_price = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    rental_price_currency = serializers.CharField(read_only = True, max_length=5)
    rental_price_period = serializers.CharField(read_only = True, max_length=50)
    property_administration_fee = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    property_administration_fee_period = serializers.CharField(read_only = True, max_length=30)
    yearly_tax = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    yearly_tax_currency = serializers.CharField(read_only = True, max_length=5)
    living_area = serializers.IntegerField(read_only = True)
    living_area_unit = serializers.CharField(read_only = True, max_length=30)
    year_built = serializers.IntegerField(read_only = True, min_value=4, max_value=4)
    bedrooms = serializers.IntegerField(read_only = True)
    bathrooms = serializers.IntegerField(read_only = True)
    garage = serializers.IntegerField(read_only = True)
    garage_type = serializers.CharField(read_only = True, max_length=30)
    unit_floor = serializers.IntegerField(read_only = True)
    unit_number = serializers.CharField(read_only = True, max_length=30)
    publish_date = serializers.DateTimeField(read_only=True, default=None)
    sync_date = serializers.DateTimeField(read_only=True, default=None)
    region_id = serializers.IntegerField(read_only = True)
    usage_id = serializers.IntegerField(read_only = True)
    type_id = serializers.IntegerField(read_only = True)
    office_id = serializers.IntegerField(read_only = True)
    agent_id = serializers.IntegerField(read_only = True)
    location_id = serializers.IntegerField(read_only = True)
    type = serializers.SerializerMethodField()
    #features = serializers.SerializerMethodField()
    medias = serializers.SerializerMethodField()
    
    
    def get_type(self, obj):
        try:
            # Get the related Type objects for the current property
            property_type = Types.objects.using('mongodb').get(type_id=obj.type_id)
            # Extract the media data from the related PropertiesMedia
            type_data = {
                    'type_id': property_type.type_id,
                    'type_name_en': property_type.type_name_en,
                    'type_name_pt': property_type.type_name_pt,
                    # Add other media fields as needed
                }
            return type_data
        except:
            return None
    

    # def get_features(self, obj):
    #     try:
    #         # Get the related PropertiesFeatures objects for the current property
    #         property_features = PropertiesFeatures.objects.using('mongodb').filter(property=obj)
    #         # Extract the feature data from the related PropertiesFeatures
    #         feature_data = [
    #             {
    #                 'feature_id': pf.feature.feature_id,
    #                 'feature_name_en': pf.feature.feature_name_en,
    #                 'feature_name_pt': pf.feature.feature_name_pt,
    #                 # Add other feature fields if needed
    #             }
    #             for pf in property_features
    #         ]
    #         return feature_data
    #     except:
    #         return None
    
    def get_medias(self, obj):
        try:
            # Get the related PropertiesMedia objects for the current property
            property_medias = PropertiesMedia.objects.using('mongodb').filter(property=obj)[:5]
            # Extract the media data from the related PropertiesMedia
            media_data = [
                {
                    'property_media_id': pm.property_media_id,
                    'type': pm.type,
                    'main': pm.main,
                    'url': pm.url,
                    # Add other media fields as needed
                }
                for pm in property_medias
            ]
            return media_data
        except:
            return None

    
    def validate(self, attrs):
        attrs['title'] = bleach.clean(attrs['title'])
        attrs['transaction_type'] = bleach.clean(attrs['transaction_type'])
        attrs['description'] = bleach.clean(attrs['description'])
        attrs['list_price_currency'] = bleach.clean(attrs['list_price_currency'])
        attrs['living_area_unit'] = bleach.clean(attrs['living_area_unit'])
        attrs['garage_type'] = bleach.clean(attrs['garage_type'])
        attrs['unit_number'] = bleach.clean(attrs['unit_number'])

        return super().validate(attrs)
    
    def validate_listing_id(self, value):
        if (value < 1):
            raise serializers.ValidationError('Listing ID must be equal or higher than 1!')
        return value
      
    class Meta:
        model = Properties
        fields = '__all__'
        #exclude = ['office', 'agent', 'location']
        depth = 0
        

class PropertyMediaSerializer(serializers.ModelSerializer):
    
    id = serializers.CharField(read_only = True)
    property_media_id = serializers.IntegerField(read_only = True, min_value=1, 
                                                 validators=[UniqueValidator(queryset=PropertiesMedia.objects.using('mongodb').all())])
    type = serializers.CharField(read_only = True, max_length=20)
    main = serializers.IntegerField(read_only = True, min_value=0, max_value=1)
    #url = serializers.SerializerMethodField()
    url = serializers.URLField(read_only = True, min_length=None, allow_blank=False)
    #property = serializers.SlugRelatedField(read_only=True, many=True, slug_field='properties')
    #property = serializers.PrimaryKeyRelatedField(read_only=True)
    
    # def get_url(self, instance):
    #     url_instance = instance.url
    #     type_instance = instance.type
    #     image_formats = ("image/png", "image/jpeg", "image/jpg", "image/gif")
        
    #     try:
    #         response = requests.head(url_instance, verify=False)
    #         if type_instance=='video':
    #             return url_instance
    #         elif instance.type=='image' and response.status_code == 200 and response.headers["content-type"] in image_formats:
    #             return url_instance
    #     except Exception as e:
    #         pass  # Image doesn't exist or couldn't be accessed
    #     return None


    def validate(self, attrs):
        attrs['type'] = bleach.clean(attrs['type'])
        return super().validate(attrs)
    
    def validate_property_media_id(self, value):
        if (value < 1):
            raise serializers.ValidationError('Property Media ID must be equal or higher than 1!')
        return value
      
    class Meta:
        model = PropertiesMedia
        fields = '__all__'



class PropertyFeatureSerializer(serializers.ModelSerializer):
    
    id = serializers.CharField(read_only = True)
    property_feature_id = serializers.IntegerField(read_only = True, min_value=1, 
                                                 validators=[UniqueValidator(queryset=PropertiesFeatures.objects.using('mongodb').all())])
    feature = serializers.PrimaryKeyRelatedField(read_only=True)
    property = serializers.PrimaryKeyRelatedField(read_only=True)

    
    def validate_property_feature_id(self, value):
        if (value < 1):
            raise serializers.ValidationError('Property Feature ID must be equal or higher than 1!')
        return value
    
    def validate_feature_id(self, value):
        if (value < 1):
            raise serializers.ValidationError('Feature ID must be equal or higher than 1!')
        return value
    

      
    class Meta:
        model = PropertiesFeatures
        fields = ['id','property_feature_id', 'feature', 'property']



# Dynamic model serializer
# from rest_framework_mongoengine.serializers import DocumentSerializer

# class PropertiesCompleteSerializer(DocumentSerializer):
#     class Meta:
#         model = PropertiesComplete
#         fields = '__all__'




# class OrderedDictField(serializers.Field):
#     def to_representation(self, value):
#         if isinstance(value, OrderedDict):
#             return {k: str(v) if isinstance(v, ObjectId) else v for k, v in value.items()}
#         elif isinstance(value, list):
#             return [str(v) if isinstance(v, ObjectId) else v for v in value]
#         return value

#     def to_internal_value(self, data):
#         return data

# class PropertiesNestedSerializer(serializers.Serializer):
    
#     class Meta:
#         model = PropertiesNested
#         fields = '__all__'
    

#     id = serializers.CharField(read_only = True)
#     property_id = serializers.IntegerField(read_only = True)
#     listing_id = serializers.CharField(read_only = True)
#     title = serializers.CharField(read_only = True)
#     transaction_type = serializers.CharField(read_only = True)
#     detail_view_url = serializers.URLField(read_only = True)
#     description = serializers.CharField(read_only=True)
#     list_price = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
#     list_price_currency = serializers.CharField(read_only = True)
#     rental_price = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
#     rental_price_currency = serializers.CharField(read_only = True)
#     rental_price_period = serializers.CharField(read_only = True)
#     property_administration_fee = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
#     property_administration_fee_period = serializers.CharField(read_only = True)
#     yearly_tax = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
#     yearly_tax_currency = serializers.CharField(read_only = True)
#     living_area = serializers.IntegerField(read_only = True)
#     living_area_unit = serializers.CharField(read_only = True)
#     year_built = serializers.IntegerField(read_only = True)
#     bedrooms = serializers.IntegerField(read_only = True)
#     bathrooms = serializers.IntegerField(read_only = True)
#     garage = serializers.IntegerField(read_only = True)
#     garage_type = serializers.CharField(read_only = True)
#     unit_floor = serializers.IntegerField(read_only = True)
#     unit_number = serializers.CharField(read_only = True)
#     publish_date = serializers.DateTimeField(read_only=True)
#     sync_date = serializers.DateTimeField(read_only=True)
#     transfer_date = serializers.DateTimeField(read_only=True)
#     #region_id = serializers.IntegerField(read_only = True)
#     usage = OrderedDictField()
#     type = OrderedDictField()
#     office = OrderedDictField()
#     agent = OrderedDictField()
#     location = OrderedDictField()
#     medias = OrderedDictField()
#     features = OrderedDictField()
    

class PropertySimpleSerializer(serializers.ModelSerializer):
    
    class Meta:
        model = Properties
        fields = '__all__'
        
        
class PropertiesNestedSimpleSerializer(serializers.Serializer):
    
    id = serializers.CharField(read_only = True)
    property_id = serializers.IntegerField(read_only = True)
    listing_id = serializers.CharField(read_only = True)
    #title = serializers.CharField(read_only = True)
    transaction_type = serializers.CharField(read_only = True)
    detail_view_url = serializers.URLField(read_only = True)
    #description = serializers.CharField(read_only=True)
    list_price = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    list_price_currency = serializers.CharField(read_only = True)
    rental_price = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    rental_price_currency = serializers.CharField(read_only = True)
    #rental_price_period = serializers.CharField(read_only = True)
    #property_administration_fee = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    #property_administration_fee_period = serializers.CharField(read_only = True)
    rental_price_period = OrderedDictField()
    property_administration_fee_period = OrderedDictField()
    yearly_tax = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    yearly_tax_currency = serializers.CharField(read_only = True)
    living_area = serializers.IntegerField(read_only = True)
    living_area_unit = serializers.CharField(read_only = True)
    year_built = serializers.IntegerField(read_only = True)
    bedrooms = serializers.IntegerField(read_only = True)
    bathrooms = serializers.IntegerField(read_only = True)
    garage = serializers.IntegerField(read_only = True)
    garage_type = serializers.CharField(read_only = True)
    unit_floor = serializers.IntegerField(read_only = True)
    unit_number = serializers.CharField(read_only = True)
    publish_date = serializers.DateTimeField(read_only=True)
    sync_date = serializers.DateTimeField(read_only=True)
    region_id = serializers.IntegerField(read_only = True)
    lat = serializers.FloatField(read_only = True)
    lng = serializers.FloatField(read_only = True)
    usage = OrderedDictField()
    type = OrderedDictField()
    office = OrderedDictField()
    agent = OrderedDictField()
    location = OrderedDictField()
    
    class Meta:
        model = PropertiesNested
        #fields = ['id', 'property_id', 'listing_id', 'title', 'transaction_type', 'detail_view_url', 'description', 'list_price', 'list_price_currency', 'rental_price', 'rental_price_currency', 'rental_price_period', 'property_administration_fee', 'property_administration_fee_period', 'yearly_tax', 'yearly_tax_currency', 'living_area', 'living_area_unit', 'year_built', 'bedrooms', 'bathrooms', 'garage', 'garage_type', 'unit_floor', 'unit_number', 'publish_date', 'sync_date', 'region_id', 'usage', 'type', 'office', 'agent', 'location']
        fields = '__all__'


def aggregate_properties_by_location(state=None, city=None):
    pipeline = [
        {
            '$unwind': '$location'  # Unwind the location array to work with individual elements
        }
    ]

    if state or city:
        match_stage = {'$match': {}}
        if state:
            match_stage['$match']['location.state'] = state
        if city:
            match_stage['$match']['location.city'] = city
        pipeline.append(match_stage)

    pipeline.extend([
        {
            '$group': {
                '_id': {
                    'state': '$location.state',
                    'city': '$location.city'
                },
                'total_properties': {'$sum': 1}
            }
        },
        {
            '$group': {
                '_id': '$_id.state',
                'cities': {
                    '$push': {
                        'city': '$_id.city',
                        'total_properties': '$total_properties'
                    }
                },
                'total_properties_in_state': {'$sum': '$total_properties'}
            }
        },
        {
            '$project': {
                '_id': 0,
                'state': '$_id',
                'cities': 1,
                'total_properties_in_state': 1
            }
        }
    ])

    #print(f"Pipeline: {pipeline}")

    aggregated_data = list(PropertiesNested.objects.mongo_aggregate(pipeline))

    return aggregated_data

class LocationAggregateSerializer(serializers.Serializer):
    def to_representation(self, instance):
        return instance

class PropertiesNestedAggregateSerializer(serializers.Serializer):
    location_aggregate = serializers.SerializerMethodField()

    def get_location_aggregate(self, obj):
        state = self.context.get('state')
        city = self.context.get('city')
        aggregated_data = aggregate_properties_by_location(state=state, city=city)
        result = {}
        for data in aggregated_data:
            state = data['state']
            cities = {item['city']: item['total_properties'] for item in data['cities']}
            cities['Total'] = data['total_properties_in_state']
            result[state] = [cities]
        return result

    

from panel.models import LancamentoNested, LancamentoUnidadeNested
class LancamentoNestedSerializer(serializers.Serializer):
    
    id = serializers.CharField(read_only=True)
    nome_do_empreendimento = serializers.CharField(read_only=True)
    logo = serializers.URLField(read_only = True)
    descricao = serializers.CharField(read_only=True)
    endereco = serializers.CharField(read_only=True)
    pais = serializers.CharField(read_only=True)
    latitude = serializers.CharField(read_only=True)
    longitude = serializers.CharField(read_only=True)
    estagio_de_obra = serializers.CharField(read_only=True)
    lancamento_id = OrderedDictField()
    bairro = OrderedDictField()
    cidade = OrderedDictField()
    estado = OrderedDictField()
    caracteristicas = OrderedDictField()
    fotos = OrderedDictField()
    plantas = OrderedDictField()
    created_at = serializers.DateTimeField(read_only=True)
    updated_at = serializers.DateTimeField(read_only=True)
    
    class Meta:
        model=LancamentoNested
        fields='__all__'



from panel.models import LancamentoUnidadeNested
class LancamentoUnidadeNestedSerializer(serializers.Serializer):
    id = serializers.CharField(read_only=True)
    codigo = serializers.CharField(read_only=True)
    descricao = serializers.CharField(read_only=True)
    quartos = serializers.IntegerField(read_only = True)
    vagas = serializers.IntegerField(read_only = True)
    banheiros = serializers.IntegerField(read_only = True)
    area = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    preco = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    status = serializers.CharField(read_only=True)
    lancamento_unidade_id = OrderedDictField()
    planta = OrderedDictField()
    lancamento = OrderedDictField()
    fotos = OrderedDictField()
    created_at = serializers.DateTimeField(read_only=True)
    updated_at = serializers.DateTimeField(read_only=True)

    class Meta:
        model=LancamentoUnidadeNested
        fields='__all__'
        
        
        
        


############################################################################################################
class PropertiesNestedSerializer(serializers.Serializer):
    
    class Meta:
        model = PropertiesNested
        #fields = '__all__'
    

    id = serializers.CharField(read_only = True)
    property_id = serializers.IntegerField(read_only = True)
    listing_id = serializers.CharField(read_only = True)
    #title = serializers.CharField(read_only = True)
    transaction_type = serializers.CharField(read_only = True)
    detail_view_url = serializers.URLField(read_only = True)
    #description = serializers.CharField(read_only=True)
    #list_price = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    list_price_currency = serializers.CharField(read_only = True)
    rental_price_currency = serializers.CharField(read_only = True)
    #rental_price_period = serializers.CharField(read_only = True)
    #property_administration_fee = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    #property_administration_fee_period = serializers.CharField(read_only = True)
    yearly_tax = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    yearly_tax_currency = serializers.CharField(read_only = True)
    living_area = serializers.DecimalField(read_only = True, max_digits=10, decimal_places=2)
    living_area_unit = serializers.CharField(read_only = True)
    year_built = serializers.IntegerField(read_only = True)
    bedrooms = serializers.IntegerField(read_only = True)
    bathrooms = serializers.IntegerField(read_only = True)
    garage = serializers.IntegerField(read_only = True)
    garage_type = serializers.CharField(read_only = True)
    unit_floor = serializers.IntegerField(read_only = True)
    unit_number = serializers.CharField(read_only = True)
    publish_date = serializers.DateTimeField(read_only=True)
    sync_date = serializers.DateTimeField(read_only=True)
    transfer_date = serializers.DateTimeField(read_only=True)
    #region_id = serializers.IntegerField(read_only = True)
    lat = serializers.FloatField(read_only = True)
    lng = serializers.FloatField(read_only = True)
    # OrderDict Fields
    rental_price_period = OrderedDictField()
    property_administration_fee_period = OrderedDictField()
    usage = OrderedDictField()
    type = OrderedDictField()
    office = OrderedDictField()
    agent = OrderedDictField()
    location = OrderedDictField()
    descriptions = OrderedDictField()
    medias = OrderedDictField()
    features = OrderedDictField()
    
    
    # New Fields
    number_units_building = serializers.IntegerField(read_only = True)
    availability_date = serializers.DateTimeField(read_only = True)
    commercial_residential = serializers.CharField(read_only = True)
    total_area = serializers.DecimalField(read_only=True, max_digits=10, decimal_places=2)
    show_hide_flag = serializers.BooleanField(read_only = True)
    show_address_on_web = serializers.BooleanField(read_only = True)
    is_public_available = serializers.BooleanField(read_only = True)
    number_of_toilet_rooms = serializers.IntegerField(read_only = True)
    total_num_of_rooms = serializers.IntegerField(read_only = True)
    hide_price_public = serializers.BooleanField(read_only = True)
    youtube_url = serializers.URLField(read_only = True)
    tour_virtual_url = serializers.URLField(read_only = True)
    # OrderDict Fields
    market_status = OrderedDictField()
    listing_status = OrderedDictField()
    floor_level = OrderedDictField()
    
    
    list_price = serializers.DecimalField(max_digits=20, decimal_places=2, coerce_to_string=False)
    rental_price = serializers.DecimalField(max_digits=20, decimal_places=2, allow_null=True, coerce_to_string=False)
    #property_administration_fee = serializers.DecimalField(max_digits=20, decimal_places=2, allow_null=True, coerce_to_string=False)

    def to_representation(self, instance):
        data = super().to_representation(instance)
        # Safely convert Decimal to float for JSON response
        for field in ['list_price', 'rental_price']:
            if field in data and isinstance(data[field], Decimal):
                data[field] = float(data[field])
        return data
    
    
        #   # new fields
    # number_units_building = models.IntegerField(null=True, default=None)
    # availability_date = models.DateTimeField(null=True, default=None)
    # commercial_residential = models.CharField(max_length=50, null=True, default=None)
    # total_area = models.DecimalField(null=True, max_digits=10, decimal_places=2)
    # show_hide_flag = models.BooleanField(null=True, default=None)
    # show_address_on_web = models.BooleanField(null=True, default=None)
    # is_public_available = models.BooleanField(null=True, default=None)
    # number_of_toilet_rooms = models.IntegerField(null=True, default=None)
    # total_num_of_rooms = models.IntegerField(null=True, default=None)
    # hide_price_public = models.BooleanField(null=True, default=None)
    # youtube_url = models.URLField(max_length=255, null=True, default=None)
    # tour_virtual_url = models.URLField(max_length=255, null=True, default=None)
    # market_status = JSONField(null=True, default=None, db_column='market_status')
    # listing_status = JSONField(null=True, default=None, db_column='listing_status')
    # floor_level = JSONField(null=True, default=None, db_column='floor_level')


class StateSerializer(serializers.ModelSerializer):
    #cities = serializers.SerializerMethodField()
    details = serializers.SerializerMethodField()
    cities = OrderedDictField()
    class Meta:
        model = State
        fields = '__all__'
    
    def get_details(self, obj):
        from panel.models import EstadoDetalhe as detail
        details_queryset = detail.objects.filter(estado_id=obj.state_id)
        details_data = []
        for detail in details_queryset:
            detail_data = {
                'text': detail.texto,
                'image': detail.imagem
            }
            details_data.append(detail_data)
            import json
            details_data = json.loads(json.dumps(details_data, default=str))
            return details_data
        
    # def get_cities(self, obj):
    #     try:
    #         cities_queryset = City.objects.filter(state_id=obj.state_id)
    #         # Extract the city data from the related City Object
    #         cities_data = []
    #         for city in cities_queryset:
    #             city_data = {
    #                 'id': str(city.id),
    #                 'city_id': city.city_id,
    #                 'city_name': city.city_name,
    #                 'details': []
    #             }
                
    #             from panel.models import CidadeDetalhe as detail
    #             cities_details_queryset = detail.objects.filter(cidade_id=city.city_id)
    #             for detail in cities_details_queryset:
    #                 detail_data = {
    #                     'text': detail.texto,
    #                     'image': detail.imagem
    #                 }
    #                 city_data['details'].append(detail_data)
    #             cities_data.append(city_data)
    #         import json
    #         cities_data = json.loads(json.dumps(cities_data, default=str))
    #         return cities_data
    #     except Exception as e:
    #         print(e)
    #         return None


class CitySerializer(serializers.ModelSerializer):
    #neighborhoods = serializers.SerializerMethodField()
    details = serializers.SerializerMethodField()
    #state_details = serializers.SerializerMethodField()
    neighborhoods = OrderedDictField()
    class Meta:
        model = City
        fields = '__all__'
    
    def get_details(self, obj):
        from panel.models import CidadeDetalhe as detail
        details_queryset = detail.objects.filter(cidade_id=obj.city_id)
        details_data = []
        for detail in details_queryset:
            detail_data = {
                'text': detail.texto,
                'image': detail.imagem
            }
            details_data.append(detail_data)
            import json
            details_data = json.loads(json.dumps(details_data, default=str))
            return details_data

    # def get_state_details(self, obj):
    #     try:
    #         state = State.objects.get(state_id=obj.state_id)
    #         from panel.models import EstadoDetalhe as detail
    #         details_queryset = detail.objects.filter(estado_id=state.state_id)
    #         details_data = []
    #         for detail in details_queryset:
    #             detail_data = {
    #                 'text': detail.texto,
    #                 'image': detail.imagem
    #             }
    #             details_data.append(detail_data)
    #             import json
    #             details_data = json.loads(json.dumps(details_data, default=str))
    #             return details_data
    #     except Exception as e:
    #         print(e)
    #         return None
        
    # def get_neighborhoods(self, obj):
    #     try:
    #         neighborhoods_queryset = Neighborhood.objects.filter(city_id=obj.city_id)
    #         # Extract the city data from the related City Object
    #         neighborhoods_data = []
    #         for neighborhood in neighborhoods_queryset:
    #             neighborhood_data = {
    #                 'id': str(neighborhood.id),
    #                 'neighborhood_id': neighborhood.neighborhood_id,
    #                 'neighborhood_name': neighborhood.neighborhood_name,
    #                 'details': []
    #             }
                
    #             from panel.models import BairroDetalhe as detail
    #             neighborhoods_details_queryset = detail.objects.filter(bairro_id=neighborhood.neighborhood_id)
    #             for detail in neighborhoods_details_queryset:
    #                 detail_data = {
    #                     'text': detail.texto,
    #                     'image': detail.imagem
    #                 }
    #                 neighborhood_data['details'].append(detail_data)
    #             neighborhoods_data.append(neighborhood_data)
    #         import json
    #         neighborhoods_data = json.loads(json.dumps(neighborhoods_data, default=str))
    #         return neighborhoods_data
    #     except Exception as e:
    #         print(e)
    #         return None
        
    
class NeighborhoodSerializer(serializers.ModelSerializer):
    details = serializers.SerializerMethodField()
    #city_details = serializers.SerializerMethodField()
    #state_details = serializers.SerializerMethodField()
    class Meta:
        model = Neighborhood
        fields = '__all__'
    
    def get_details(self, obj):
        from panel.models import BairroDetalhe as detail
        details_queryset = detail.objects.filter(bairro_id=obj.neighborhood_id)
        details_data = []
        for detail in details_queryset:
            detail_data = {
                'text': detail.texto,
                'image': detail.imagem
            }
            details_data.append(detail_data)
            import json
            details_data = json.loads(json.dumps(details_data, default=str))
            return details_data
    
    # def get_city_details(self, obj):
    #     try:
    #         city = City.objects.get(city_id=obj.city_id)
    #         from panel.models import CidadeDetalhe as detail
    #         details_queryset = detail.objects.filter(cidade_id=city.city_id)
    #         details_data = []
    #         for detail in details_queryset:
    #             detail_data = {
    #                 'text': detail.texto,
    #                 'image': detail.imagem
    #             }
    #             details_data.append(detail_data)
    #             import json
    #             details_data = json.loads(json.dumps(details_data, default=str))
    #             return details_data
    #     except Exception as e:
    #         print(e)
    #         return None
    
    # def get_state_details(self, obj):
    #     try:
    #         state = State.objects.get(state_id=obj.state_id)
    #         from panel.models import EstadoDetalhe as detail
    #         details_queryset = detail.objects.filter(estado_id=state.state_id)
    #         details_data = []
    #         for detail in details_queryset:
    #             detail_data = {
    #                 'text': detail.texto,
    #                 'image': detail.imagem
    #             }
    #             details_data.append(detail_data)
    #             import json
    #             details_data = json.loads(json.dumps(details_data, default=str))
    #             return details_data
    #     except Exception as e:
    #         print(e)
    #         return None
        
        
        
        



#############


class StateSimpleSerializer(serializers.ModelSerializer):
    details = serializers.SerializerMethodField()
    class Meta:
        model = State
        exclude = ['cities']
    
    def get_details(self, obj):
        from panel.models import EstadoDetalhe as detail
        details_queryset = detail.objects.filter(estado_id=obj.state_id)
        details_data = []
        for detail in details_queryset:
            detail_data = {
                'text': detail.texto,
                'image': detail.imagem
            }
            details_data.append(detail_data)
            import json
            details_data = json.loads(json.dumps(details_data, default=str))
            return details_data
        



class CitySimpleSerializer(serializers.ModelSerializer):
    details = serializers.SerializerMethodField()
    class Meta:
        model = City
        exclude = ['neighborhoods']
    
    def get_details(self, obj):
        from panel.models import CidadeDetalhe as detail
        details_queryset = detail.objects.filter(cidade_id=obj.city_id)
        details_data = []
        for detail in details_queryset:
            detail_data = {
                'text': detail.texto,
                'image': detail.imagem
            }
            details_data.append(detail_data)
            import json
            details_data = json.loads(json.dumps(details_data, default=str))
            return details_data


        
    
class NeighborhoodSimpleSerializer(serializers.ModelSerializer):
    details = serializers.SerializerMethodField()
    class Meta:
        model = Neighborhood
        fields = '__all__'
    
    def get_details(self, obj):
        from panel.models import BairroDetalhe as detail
        details_queryset = detail.objects.filter(bairro_id=obj.neighborhood_id)
        details_data = []
        for detail in details_queryset:
            detail_data = {
                'text': detail.texto,
                'image': detail.imagem
            }
            details_data.append(detail_data)
            import json
            details_data = json.loads(json.dumps(details_data, default=str))
            return details_data
    


    
    

    
    
