from library.models import *
from .models import *
from rest_framework import serializers
from django.contrib.auth import authenticate, get_user_model
from datetime import date
from django.conf import settings


class UserLoginSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField(write_only=True)

    class Meta:
        model = CustomUser
        fields = ['username', 'password']

    def validate(self, data):
        username = data.get('username')
        password = data.get('password')

        if username and password:
            user = authenticate(request=self.context.get('request'), username=username, password=password)

            if not user:
                msg = 'Unable to log in with provided credentials.'
                raise serializers.ValidationError(msg, code='authorization')

            data['user'] = user
        else:
            msg = 'Must include "username" and "password".'
            raise serializers.ValidationError(msg, code='authorization')

        return data

class UserLogoutSerializer(serializers.Serializer):
    token = serializers.CharField()

class ChangePasswordSerializer(serializers.Serializer):
    old_password = serializers.CharField(required=True)
    new_password = serializers.CharField(required=True)

class MemberRegistrationSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomUser
        fields = ['username', 'email', 'password']
        extra_kwargs = {"password": {"write_only": True}}

    def create(self, validated_data):
        username=validated_data["username"]
        email=validated_data["email"]
        user = CustomUser(username=username, email=email)
        user.set_password(validated_data["password"])
        user.save()
        return user

class LibrarianRegistrationSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomUser
        fields = ['username', 'email', 'password', 'is_librarian']
        extra_kwargs = {"password": {"write_only": True}}

    def create(self, validated_data):
        username=validated_data["username"]
        email=validated_data["email"]
        is_librarian=validated_data["is_librarian"]
        user = CustomUser(username=username, email=email, is_librarian=is_librarian)
        user.set_password(validated_data["password"])
        user.save()
        return user

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = CustomUser
        fields = ['email', 'first_name', 'last_name']

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ['name']

class BookSerializer(serializers.ModelSerializer):
    category = CategorySerializer()

    class Meta:
        model = Book
        fields = '__all__'

class BookSearchSerializer(serializers.Serializer):
    book_name = serializers.CharField(max_length=255)

class MemberSerializer(serializers.ModelSerializer):
    class Meta:
        model = Member
        fields = '__all__'

class LibrarianSerializer(serializers.ModelSerializer):
    class Meta:
        model = Librarian
        fields = '__all__'

from rest_framework import serializers

class BookLoanSerializer(serializers.ModelSerializer):
    book_image_url = serializers.SerializerMethodField()
    book_title = serializers.SerializerMethodField()
    member_name = serializers.SerializerMethodField()
    loan_date = serializers.DateField(format='%Y-%m-%d', read_only=True)
    due_date = serializers.DateField(format='%Y-%m-%d', read_only=True)
    return_date = serializers.DateField(format='%Y-%m-%d', read_only=True)

    class Meta:
        model = BookLoan
        fields = ['book_image_url', 'book_title', 'member_name', 'loan_date', 'due_date', 'return_date', 'is_returned']

    def get_book_image_url(self, obj):
        if obj.book.image:
            request = self.context.get('request')
            return request.build_absolute_uri(obj.book.image.url)
        return None

    def get_book_title(self, obj):
        return obj.book.title

    def get_member_name(self, obj):
        return obj.member.name


class OverdueLoanSerializer(serializers.ModelSerializer):
    days_over = serializers.SerializerMethodField()
    book_title = serializers.CharField(source='book.title')
    book_image_url = serializers.SerializerMethodField()
    member_name = serializers.CharField(source='member.name')

    class Meta:
        model = BookLoan
        fields = '__all__'

    def get_book_image_url(self, obj):
        if obj.book.image:
            request = self.context.get('request')
            return request.build_absolute_uri(obj.book.image.url)
        return None

    def get_days_over(self, obj):
        return (date.today() - obj.due_date).days
    
class NearOutstandingLoanSerializer(serializers.ModelSerializer):
    days_left = serializers.SerializerMethodField()
    book_title = serializers.CharField(source='book.title')  # Tambahkan informasi judul buku
    book_image_url = serializers.SerializerMethodField()
    member_name = serializers.CharField(source='member.name') 

    class Meta:
        model = BookLoan
        fields = '__all__'

    def get_days_left(self, obj):
        return (obj.due_date - date.today()).days
    
    def get_book_image_url(self, obj):
        if obj.book.image:
            request = self.context.get('request')
            return request.build_absolute_uri(obj.book.image.url)
        return None
    
class MemberBookLoanSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookLoan
        fields = ['book','due_date']

class MemberBookLoanByIdSerializer(serializers.ModelSerializer):
    class Meta:
        model = BookLoan
        fields = ['due_date']

class BookMemberSerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField('get_book_image_url')

    class Meta:
        model = Book
        fields = ['title', 'image']

    def get_book_image_url(self, obj):
        if obj.image:
            return self.context['request'].build_absolute_uri(obj.image.url)
        return None

class BookLoanMemberSerializer(serializers.ModelSerializer):
    def to_representation(self, instance):
        request = self.context.get('request')
        book_serializer = BookMemberSerializer(instance.book, context={'request': request})
        return {
            'book_info': book_serializer.data,
            'due_date': instance.due_date,
            'is_returned': instance.is_returned
        }

    class Meta:
        model = BookLoan
        fields = ['book_info', 'due_date', 'is_returned']