from rest_framework import serializers

from base.serializer import UserSerializerMixin, BaseSerializer
from market.serializers import MarketSerializer
from .models import Order, Catalogue


class ReadWriteSerializerMethodField(serializers.SerializerMethodField):
    
    def __init__(self, method_name=None, **kwargs):
        self.method_name = method_name
        kwargs['source'] = '*'
        super(serializers.SerializerMethodField, self).__init__(**kwargs)

    def to_internal_value(self, data):
        return {self.field_name: data}

class OrderSerializer(UserSerializerMixin):
    order = ReadWriteSerializerMethodField()
    
    class Meta:
        model = Order
        fields = ('id', 'user', 'status', 'order',)
        read_only_fields = ('user', 'status', 'order')
        
    @staticmethod
    def get_order(obj):
        return CatalogueSerializer(obj.order).data
        
    def create(self, validated_data):
        user = self.request.user
        order = validated_data.pop('order')
        return self.Meta.model.objects.create(
            user=user,
            status="started",
            order=Catalogue.objects.get(id=order)
        )


class CatalogueSerializer(BaseSerializer):
    market = ReadWriteSerializerMethodField()
    price = ReadWriteSerializerMethodField()
    delivery_time = serializers.SerializerMethodField()
    
    @staticmethod
    def get_delivery_time(obj):
        return obj.get_delivery_time
    
    @staticmethod
    def get_price(obj):
        return obj.get_price
    
    class Meta:
        model = Catalogue
        fields = ('id', 'name', 'category', 'price', 'hour', 'minute', 'market', 'rating', 'delivery_time',)
        read_only_fields = ('market', 'rating',)
        extra_kwargs = {
            'hour': {'write_only': True},
            'minute': {'write_only': True},
        }
    
    @staticmethod
    def get_market(obj):
        return MarketSerializer(obj.market).data
        
    def create(self, validated_data):
        market = self.request.market
        validated_data['market'] = market
        return super(CatalogueSerializer, self).create(validated_data)
