from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers

from establishment.models import Establishment
from location.models import Country
from main.models import Carousel
from news.models import News


def get_obj_data(model, slug):
    try:
        obj = model.objects.get(slug=slug)
    except model.DoesNotExist:
        return None, None
    else:
        content_type = ContentType.objects.get_for_model(obj)
        return obj.id, content_type.id


class CarouselSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    title = serializers.CharField(allow_null=True, allow_blank=True)
    link = serializers.CharField(allow_null=True)
    link_title = serializers.CharField(allow_null=True, allow_blank=True)
    description = serializers.CharField(allow_null=True, allow_blank=True)
    attachment_suffix_url = serializers.CharField(allow_null=True)
    active = serializers.IntegerField()
    country = serializers.CharField(allow_null=True)

    def create(self, validated_data):
        object_id, content_type_id = self.get_content_type(validated_data)
        validated_data.update({
            'old_id': validated_data['id'],
            'country': self.get_country(validated_data),
            'active': bool(int(validated_data['active'])),
            'content_type_id': content_type_id,
            'object_id': object_id,
            'is_parse': bool(object_id),
        })
        validated_data.pop('id')
        obj, _ = Carousel.objects.update_or_create(**validated_data)
        return obj

    @staticmethod
    def get_country(data):
        return Country.objects.filter(code__iexact=data['country']).first()

    @staticmethod
    def get_content_type(data):
        link = data['link']
        if not link:
            return None

        obj_data = None, None
        site = 'gaultmillau.com'
        if site in link:
            data = link.split('/')

            try:
                _type = data[3]
            except IndexError:
                pass
            else:
                if _type in ('news', 'pages'):
                    obj_data = get_obj_data(News, data[4])
                elif _type == 'restaurant':
                    obj_data = get_obj_data(Establishment, data[4])
        return obj_data
