from rest_framework import serializers

from establishment.models import Menu, Plate, Establishment
from main.models import Currency
from utils.constants import CODE_LOCALES


class PlateSerializer(serializers.Serializer):
    name = serializers.CharField()
    price = serializers.DecimalField(decimal_places=2, max_digits=10)
    currency = serializers.CharField()
    dish_type = serializers.CharField()
    country_code = serializers.CharField()
    establishment_id = serializers.IntegerField()
    signature = serializers.IntegerField(allow_null=True)

    def create(self, validated_data):
        establishment = Establishment.objects.filter(old_id=validated_data['establishment_id']).first()
        if not establishment:
            return
        return Plate.objects.create(**self.get_plate_data(validated_data, establishment.id))

    def get_plate_data(self, validated_data, est_id):
        locale = CODE_LOCALES.get(validated_data['country_code'], 'en-GB')
        payload = {
            'name': {locale: validated_data['name']},
            'price': validated_data['price'],
            'currency_id': self.get_currency(validated_data),
            'menu_id': self.get_menu(validated_data, est_id),
            'is_signature_plate': bool(validated_data['signature']),
        }
        return payload

    @staticmethod
    def get_menu(validated_data, est_id):
        payload = {
            'establishment_id': est_id,
            'category': {'en-GB': validated_data['dish_type']},
        }
        menu, _ = Menu.objects.get_or_create(**payload)
        return menu.id

    @staticmethod
    def get_currency(validated_data):
        try:
            currency = Currency.objects.get(
                slug=validated_data['currency'],
                sign='$',
            )
        except Currency.DoesNotExist:
            currency = Currency.objects.create(
                slug=validated_data['currency'],
                sign='$',
            )
        return currency.id
