from rest_framework import serializers
from main.models import SiteSettings

from transfer.models import Sites, Ads
from advertisement.models import Advertisement
from main.models import Page
import requests
from rest_framework import status


class AdvertisementSerializer(serializers.ModelSerializer):

    id = serializers.IntegerField()
    href = serializers.CharField()
    site_id = serializers.PrimaryKeyRelatedField(
        queryset=Sites.objects.all())

    class Meta:
        """Meta class."""
        model = Advertisement
        fields = [
            'id',
            'href',
            'site_id',
        ]

    def validate(self, data):
        data.update({
            'old_id': data.pop('id'),
            'url': data.pop('href'),
            'site_settings': self.get_site_settings(data.pop('site_id')),
        })
        return data

    def create(self, validated_data):
        site = validated_data.pop('site_settings')
        url = validated_data.get('url')

        obj, _ = self.Meta.model.objects.get_or_create(url=url, defaults=validated_data)

        if site and site not in obj.sites.all():
            obj.sites.add(site)
        return obj

    def get_site_settings(self, subdomain):
        subdomain = subdomain.country_code_2 if isinstance(subdomain, Sites) else subdomain
        qs = SiteSettings.objects.filter(subdomain=subdomain)
        if qs.exists():
            return qs.first()


class AdvertisementImageSerializer(AdvertisementSerializer):

    attachment_suffix_url = serializers.CharField()

    class Meta(AdvertisementSerializer.Meta):
        model = Page
        fields = [
            'id',
            'attachment_suffix_url',
        ]

    def validate(self, data):
        data.update({
            'image_url': self.get_absolute_image_url(data.pop('attachment_suffix_url')),
            'advertisement': self.get_advertisement(data.pop('id')),
        })
        return data

    def get_advertisement(self, old_id):
        qs = Advertisement.objects.filter(old_id=old_id)
        if qs.exists():
            return qs.first()

    def get_absolute_image_url(self, relative_path):
        if relative_path:
            absolute_image_url = f'https://1dc3f33f6d-3.optimicdn.com/gaultmillau.com/' \
                                 f'{relative_path}'
            response = requests.head(absolute_image_url)
            if response.status_code == status.HTTP_200_OK:
                return absolute_image_url

    def create(self, validated_data):
        advertisement = validated_data.get('advertisement')
        image_url = validated_data.get('image_url')

        if advertisement and image_url:
            self.Meta.model.objects.get_or_create(source=Page.MOBILE, **validated_data)
            self.Meta.model.objects.get_or_create(source=Page.WEB, **validated_data)
