import json

from rest_framework import serializers as serializer

from console.APP.models import Drafts, VersionUpdate, UserLocation

from common.accounts.models import Users


class OrderSettingSerialzier(serializer.Serializer):
    order_rec_setting = serializer.BooleanField(required=True,
                                                allow_null=False)

    def update(self, instance, validated_data):
        instance.order_rec_setting = validated_data.get("order_rec_setting")
        instance.save()
        return instance


class DraftsCreateSerialzier(serializer.Serializer):
    title = serializer.CharField(required=True,
                                 allow_null=False,
                                 allow_blank=False)
    index = serializer.CharField(required=True,
                                 allow_null=False,
                                 allow_blank=False)
    content = serializer.DictField(required=True, allow_empty=False)

    def create(self, validated_data):
        request = self.context.get("request")
        user = Users.objects.filter(account=request.user).first()
        drafts = Drafts.objects.create(title=validated_data.get("title"),
                                       index=validated_data.get("index"),
                                       content=json.dumps(
                                           validated_data.get("content"),
                                           ensure_ascii=False),
                                       user=user if user else None)
        return drafts


class DraftsInfoSerialzier(serializer.ModelSerializer):
    def to_representation(self, instance):
        return {
            "id": instance.id,
            "title": instance.title,
            "index": instance.index,
            "content": json.loads(instance.content)
        }

    class Meta:
        model = Drafts
        fields = ("id", "title", "index", "content")


class UserLocationCreateSerializer(serializer.Serializer):
    location = serializer.CharField(required=True,
                                    allow_blank=False,
                                    allow_null=False)

    def create(self, validated_data):
        request = self.context.get("request")
        user_location = UserLocation.objects.create(
            user=Users.objects.filter(account=request.user,
                                      deleted=False).first(),
            location=validated_data.get("location"))
        return user_location


class VersionUpdateSerializer(serializer.ModelSerializer):
    class Meta:
        model = VersionUpdate
        fields = ("id", "version", "is_updated", "package_url")
