"""Back account serializers"""
from rest_framework import serializers
from partner.models import Partner, PartnerToEstablishment
from establishment.serializers import EstablishmentShortSerializer
from location.serializers import CountrySimpleSerializer
from location.models import Country
from django.shortcuts import get_object_or_404
from establishment.models import Establishment


class BackPartnerSerializer(serializers.ModelSerializer):
    # establishments = EstablishmentShortSerializer(many=True, read_only=True, source='establishment')
    country = CountrySimpleSerializer(read_only=True)
    type_display = serializers.CharField(read_only=True)
    country_id = serializers.PrimaryKeyRelatedField(
        queryset=Country.objects.all(),
        required=False,
        write_only=True,
        source='country'
    )

    class Meta:
        model = Partner
        fields = (
            'id',
            'name',
            'images',
            'type',
            'type_display',
            'country',
            'country_id',
            # 'establishments',
        )
        extra_kwargs = {
            'type': {'write_only': True},
        }


class PartnersForEstablishmentSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(source='partner.pk', read_only=True)
    bind_id = serializers.IntegerField(source='id', read_only=True)
    name = serializers.CharField(source='partner.name', read_only=True)
    type = serializers.IntegerField(source='partner.type', read_only=True)
    type_display = serializers.CharField(source='partner.type_display', read_only=True)
    country = CountrySimpleSerializer(read_only=True, source='partner.country')

    class Meta:
        model = PartnerToEstablishment
        fields = (
            'id',
            'bind_id',
            'name',
            'type',
            'type_display',
            'starting_date',  # own field
            'expiry_date',  # own field
            'price_per_month',  # own field
            'country',
            'url',  # own field
            'image',  # own field
        )

    def create(self, validated_data):
        establishment_id = self.context['view'].kwargs['establishment_id']
        partner_id = self.context['view'].kwargs['partner_id']
        establishment = get_object_or_404(Establishment, pk=establishment_id)
        partner = get_object_or_404(Partner, pk=partner_id)
        instance = PartnerToEstablishment.objects.create(**validated_data,
                                                         establishment=establishment,
                                                         partner=partner)
        return instance


class PartnerPicturesSerializer(serializers.ModelSerializer):

    class Meta:
        model = Partner
        fields = (
            'images',
        )
