from rest_framework import serializers

from account.models import User
from gallery.models import Image
from location.models import Country
from news.models import News, NewsGallery
from utils.legacy_parser import parse_legacy_news_content


class NewsSerializer(serializers.Serializer):
    locale = serializers.CharField()
    page__id = serializers.IntegerField()
    news_type_id = serializers.IntegerField()
    page__created_at = serializers.DateTimeField(format='%m-%d-%Y %H:%M:%S')
    page__account_id = serializers.IntegerField(allow_null=True)
    page__state = serializers.CharField()
    page__template = serializers.CharField()
    page__site__country_code_2 = serializers.CharField(allow_null=True)
    slug = serializers.CharField()
    body = serializers.CharField(allow_null=True)
    title = serializers.CharField()
    page__root_title = serializers.CharField()
    summary = serializers.CharField(allow_null=True, allow_blank=True)
    page__attachment_suffix_url = serializers.CharField()
    page__published_at = serializers.DateTimeField(format='%m-%d-%Y %H:%M:%S', allow_null=True)

    def create(self, data):
        account = self.get_account(data)
        payload = {
            'old_id': data['page__id'],
            'news_type_id': data['news_type_id'],
            'created': data['page__created_at'],
            'created_by': account,
            'modified_by': account,
            'state': self.get_state(data),
            'template': self.get_template(data),
            'country': self.get_country(data),
            'slugs': {data['locale']: data['slug']},
            'description': self.get_description(data),
            'title': {data['locale']: data['title']},
            'backoffice_title': data['page__root_title'],
            'subtitle': self.get_subtitle(data),
            'locale_to_description_is_active': {data['locale']: True},
            'publication_date': self.get_publication_date(data),
            'publication_time': self.get_publication_time(data),
        }

        obj, created = News.objects.get_or_create(
            old_id=payload['old_id'],
            defaults=payload,
        )
        if not created:
            obj.slugs.update(payload['slugs'])
            obj.title.update(payload['title'])
            obj.locale_to_description_is_active.update(payload['locale_to_description_is_active'])

            if obj.description and payload['description']:
                obj.description.update(payload['description'])
            else:
                obj.description = payload['description']

            if obj.subtitle and payload['subtitle']:
                obj.subtitle.update(payload['subtitle'])
            else:
                obj.subtitle = payload['subtitle']

            obj.save()

        self.make_gallery(data, obj)
        return obj

    @staticmethod
    def get_publication_date(data):
        published_at = data.get('page__published_at')
        if published_at:
            return published_at.date()
        return None

    @staticmethod
    def get_publication_time(data):
        published_at = data.get('page__published_at')
        if published_at:
            return published_at.time()
        return None

    @staticmethod
    def get_account(data):
        return User.objects.filter(old_id=data['page__account_id']).first()

    @staticmethod
    def get_state(data):
        states = {
            'new': News.WAITING,
            'published': News.PUBLISHED,
            'hidden': News.HIDDEN,
            'published_exclusive': News.PUBLISHED_EXCLUSIVE,
            'scheduled_exclusively': News.WAITING,
        }
        return states.get(data['page__state'], News.WAITING)

    @staticmethod
    def get_template(data):
        templates = {
            'main': News.MAIN,
            'main.pdf.erb': News.MAIN_PDF_ERB,
            'newspaper': News.NEWSPAPER,
        }
        return templates.get(data['page__template'], News.MAIN)

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

    @staticmethod
    def get_description(data):
        if data['body']:
            content = parse_legacy_news_content(data['body'])
            return {data['locale']: content}
        return None

    @staticmethod
    def get_subtitle(data):
        if data.get('summary'):
            return {data['locale']: data['summary']}
        return None

    @staticmethod
    def make_gallery(data, obj):
        if not data['page__attachment_suffix_url'] or data['page__attachment_suffix_url'] == 'default/missing.png':
            return

        img, _ = Image.objects.get_or_create(
            image=data['page__attachment_suffix_url'],
            title=data['page__root_title'],
            created=data['page__created_at']
        )

        gal, _ = NewsGallery.objects.get_or_create(
            news=obj,
            image=img,
            is_main=True,
        )
