from rest_framework import serializers
from .models import Ticket, Message, Attachment, ContactUsModel
from django.utils.timezone import localtime
from order.serializers import OrderListSerializer
from order.serializers import OrderModel

class AttachmentSerializer(serializers.ModelSerializer):
    file = serializers.FileField(write_only=True)
    link = serializers.SerializerMethodField()

    class Meta:
        model = Attachment
        fields = ['id', 'name', 'file', 'link' , 'created_at', 'size']
        read_only_fields = ('size', 'name', )
        
    def get_link(self, obj):
        request = self.context.get('request')
        if request is not None:
            return request.build_absolute_uri(obj.file.url)
        return obj.file.url

class MessageSerializer(serializers.ModelSerializer):
    is_user = serializers.SerializerMethodField(read_only=True)
    class Meta:
        model = Message
        exclude = ('sender', )
        extra_kwargs = {'ticket': {'write_only': True}}
    def get_is_user(self, obj):
        user = self.context['request'].user
        return user == obj.sender

class MessageAttachmentSerializer(serializers.ModelSerializer):
    is_user = serializers.SerializerMethodField(read_only=True)
    attachments = AttachmentSerializer(many=True, read_only=True)
    class Meta:
        model = Message
        exclude = ('sender', )
        extra_kwargs = {'ticket': {'write_only': True}}
    def get_is_user(self, obj):
        user = self.context['request'].user
        return user == obj.sender

class MessageForTicketSerializer(serializers.ModelSerializer):
    class Meta:
        model = Message
        exclude = ('sender', 'ticket')
class TicketSerializer(serializers.ModelSerializer):
    status = serializers.SerializerMethodField()
    ticket_category = serializers.SerializerMethodField()
    messages = MessageAttachmentSerializer(many=True, read_only=True)
    message = MessageForTicketSerializer(write_only=True)
    order_id = serializers.PrimaryKeyRelatedField(queryset=OrderModel.objects.all(), write_only=True, source='order')
    order = OrderListSerializer(read_only=True)
    class Meta:
        model = Ticket
        exclude = ('customer', 'admin')
        read_only_fields = ('status',)

    def create(self, validated_data):
        message = validated_data.pop('message', None)
        ticket = super().create(validated_data)
        if message:
            message['ticket'] = ticket.pk
            if 'attachments' in message:
                message['attachments'] = [attachment.pk for attachment in message['attachments']]
            message_obj = MessageSerializer(data=message)
            if message_obj.is_valid():
                message_obj.save(sender=ticket.customer)
            else:
                raise Exception(f'error in create failed: {message_obj.errors}')
        return ticket

    def get_status(self, obj):
        return obj.get_status_display()

    def get_ticket_category(self, obj):
        return obj.get_ticket_category_display()

class TicketListSerializer(serializers.ModelSerializer):
    status = serializers.SerializerMethodField()
    ticket_category = serializers.SerializerMethodField()
    order = OrderListSerializer()
    class Meta:
        model = Ticket
        exclude = ('customer', 'admin', )
        read_only_fields = ('status',)
    def get_status(self, obj):
        return obj.get_status_display()

    def get_ticket_category(self, obj):
        return obj.get_ticket_category_display()
    

class ContactUsSerializer(serializers.ModelSerializer):
    class Meta:
        model = ContactUsModel
        fields = ['full_name', 'email', 'phone', 'type', 'message']