from rest_framework import serializers
from rest_framework.settings import api_settings

from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import ugettext as _
from django.core.paginator import Paginator
from django.http import JsonResponse

from core.models import Post



class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = get_user_model()
        fields = ('email', 'name', 'password', 'username')
        extra_kwargs = {'password': {'write_only': True, 'min_length': 8}}

    def create(self, validated_data):
        return get_user_model().objects.create_user(**validated_data)


class UserInfoSerializer(serializers.ModelSerializer):
    """User settings serializer"""

    class Meta:
        model = get_user_model()
        fields = ('email', 'name', 'username', 'password', 'bio')
        extra_kwargs = {'password': {'write_only': True, 'min_length': 8}}

    def update(self, instance, validated_data):
        
        password = validated_data.pop('password', None)
        user = super().update(instance, validated_data)

        if password:
            user.set_password(password)
            user.save()

        return user


class FollowSerializer(serializers.ModelSerializer):

    class Meta:
        model = get_user_model()
        fields = ('username',)


class UserPostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ('caption',)


class UserProfileSerializer(serializers.ModelSerializer):

    user_posts = serializers.SerializerMethodField()

    class Meta:
        model = get_user_model()
        fields = ('id', 'username', 'email', 'bio', 'user_posts')


    def paginated_user_posts(self, obj):
        page_size = api_settings.PAGE_SIZE
        paginator = Paginator(obj.user_posts.all(), page_size)
        page = self.context['request'].query_params.get('page') or 1

        user_posts = paginator.page(page)
        serializer = UserPostSerializer(user_posts, many=True)

        return serializer.data

    def get_user_posts(self, obj):
        pass


class AuthTokenSerializer(serializers.Serializer):

    email = serializers.CharField()
    username = serializers.CharField()
    password = serializers.CharField(
        style={'input_type': 'password'},
        trim_whitespace=False
    )

    def validate(self, attrs):

        email = attrs.get('email')
        username = attrs.get('username')
        password = attrs.get('password')

        user = authenticate(
            request=self.context.get('request'),
            email=email,
            username=username,
            password=password
        )
        if not user:
            msg = _('Unable to authenticate with provoided credentials')
            raise serializers.ValidationError(msg, code='authentication')

        attrs['user'] = user
        return attrs

from rest_framework import serializers
from rest_framework.settings import api_settings

from django.contrib.auth import authenticate, get_user_model
from django.utils.translation import ugettext as _
from django.core.paginator import Paginator
from django.http import JsonResponse

from core.models import Post



class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = get_user_model()
        fields = ('email', 'name', 'password', 'username')
        extra_kwargs = {'password': {'write_only': True, 'min_length': 8}}

    def create(self, validated_data):
        return get_user_model().objects.create_user(**validated_data)


class UserInfoSerializer(serializers.ModelSerializer):
    """User settings serializer"""

    class Meta:
        model = get_user_model()
        fields = ('email', 'name', 'username', 'password', 'bio')
        extra_kwargs = {'password': {'write_only': True, 'min_length': 8}}

    def update(self, instance, validated_data):
        
        password = validated_data.pop('password', None)
        user = super().update(instance, validated_data)

        if password:
            user.set_password(password)
            user.save()

        return user


class FollowSerializer(serializers.ModelSerializer):

    class Meta:
        model = get_user_model()
        fields = ('username',)


class UserPostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ('caption',)


class UserProfileSerializer(serializers.ModelSerializer):

    user_posts = serializers.SerializerMethodField()

    class Meta:
        model = get_user_model()
        fields = ('id', 'username', 'email', 'bio', 'user_posts')


    def paginated_user_posts(self, obj):
        page_size = api_settings.PAGE_SIZE
        paginator = Paginator(obj.user_posts.all(), page_size)
        page = self.context['request'].query_params.get('page') or 1

        user_posts = paginator.page(page)
        serializer = UserPostSerializer(user_posts, many=True)

        return serializer.data

    def get_user_posts(self, obj):
        pass


class AuthTokenSerializer(serializers.Serializer):

    email = serializers.CharField()
    username = serializers.CharField()
    password = serializers.CharField(
        style={'input_type': 'password'},
        trim_whitespace=False
    )

    def validate(self, attrs):

        email = attrs.get('email')
        username = attrs.get('username')
        password = attrs.get('password')

        user = authenticate(
            request=self.context.get('request'),
            email=email,
            username=username,
            password=password
        )
        if not user:
            msg = _('Unable to authenticate with provoided credentials')
            raise serializers.ValidationError(msg, code='authentication')

        attrs['user'] = user
        return attrs

User settings serializer