from django.core.exceptions import ObjectDoesNotExist
from rest_framework import viewsets
from rest_framework_jwt.serializers import User
from FiNote_API.models import AuthUser
from FiNote_API.v1.user_serializer import *
from rest_framework.response import Response


class SignUpUserViewSet(viewsets.ViewSet):
    queryset = AuthUser.objects.all()
    serializer_class = SignUpUserSerializer

    @staticmethod
    def create(request):
        """
        ユーザを作成する
        :param request: username, password, email, birthyear
        :return         user's pk
        """

        data = request.data
        serializer = SignUpUserSerializer(data=data)

        if not (serializer.is_valid() and request.method == 'POST'):
            raise serializers.ValidationError(serializer.errors)

        if User.objects.filter(username=data['username']).exists():
            raise serializers.ValidationError('このユーザ名は既に使われています')

        if User.objects.filter(email=data['email']).exists():
            raise serializers.ValidationError('このメールアドレスは既に使われています')

        user = User.objects.create_user(
            username=data['username'],
            email=data['email'],
            password=data['password'],
            birthyear=data['birthyear'],
        )

        return Response({'id': user.pk})


class SignInUserViewSet(viewsets.ViewSet):
    queryset = AuthUser.objects.all()
    serializer_class = SignInUserSerializer

    @staticmethod
    def create(request):
        """
        ユーザログインを実施
        :param request: username, password
        :return         user's pk
        """

        data = request.data
        serializer = SignInUserSerializer(data=data)

        if not (serializer.is_valid() and request.method == 'POST'):
            raise serializers.ValidationError(serializer.errors)

        try:
            user = AuthUser.objects.get(username=data['username'])
        except:
            raise serializers.ValidationError('ユーザが見つかりませんでした')

        if not user.check_password(data['password'].encode('utf-8')):
            raise serializers.ValidationError('パスワードが間違っています')

        return Response({'id': user.pk})


class UpdatePasswordViewSet(viewsets.ViewSet):
    queryset = AuthUser.objects.all()
    serializer_class = UpdatePasswordSerializer

    @staticmethod
    def create(request):
        """
        パスワードを変更する

        :param request: username, now_password, new_password
        :return:        username
        """

        data = request.data
        serializer = UpdatePasswordSerializer(data=data)

        if serializer.is_valid() and request.method == 'POST':
            try:
                user = AuthUser.objects.get(username=data['username'])

            except ObjectDoesNotExist:
                raise serializers.ValidationError('ユーザが見つかりませんでした')

            if not user.check_password(data['now_password'].encode('utf-8')):
                raise serializers.ValidationError('現在のパスワードが異なるため変更に失敗しました')

            user.set_password(data['new_password'])
            user.save()

            return Response({'username': str(user)})

        else:
            return Response(serializer.errors)


class UpdateEmailViewSet(viewsets.ViewSet):
    queryset = AuthUser.objects.all()
    serializer_class = UpdateEmailSerializer

    @staticmethod
    def create(request):
        """
        メールアドレスを変更する

        :param request: username, password, new_email
        :return:        username
        """

        data = request.data
        serializer = UpdateEmailSerializer(data=data)

        if serializer.is_valid() and request.method == 'POST':
            try:
                user = AuthUser.objects.get(username=data["username"])
            except ObjectDoesNotExist:
                raise serializers.ValidationError('ユーザが見つかりませんでした')

            if not user.check_password(data['password'].encode('utf-8')):
                raise serializers.ValidationError('パスワードが違います')

            user.email = data['new_email']
            user.save()

            return Response({'username': str(user)})

        else:
            raise serializers.ValidationError(serializer.errors)

@@ -2548,32 +2548,37 @@
 ta)%0A%0A        if 
+not (
 serializer.is_va
@@ -2603,32 +2603,33 @@
 method == 'POST'
+)
 :%0A            tr
@@ -2622,33 +2622,91 @@
             
+raise serializers.ValidationError(serializer.errors)%0A%0A        
 try:%0A
-    
             
@@ -2761,36 +2761,32 @@
 ame'%5D)%0A%0A        
-  
-  
 except ObjectDoe
@@ -2788,36 +2788,32 @@
 ctDoesNotExist:%0A
-    
             rais
@@ -2861,36 +2861,32 @@
 %E3%82%93%E3%81%A7%E3%81%97%E3%81%9F')%0A%0A        
-   
- 
 if not user.chec
@@ -2927,36 +2927,32 @@
 code('utf-8')):%0A
-    
             rais
@@ -3013,28 +3013,24 @@
 ')%0A%0A        
-    
 user.set_pas
@@ -3057,36 +3057,32 @@
 word'%5D)%0A        
- 
-   
 user.save()%0A%0A   
@@ -3070,36 +3070,32 @@
    user.save()%0A%0A
-    
         return R
@@ -3132,70 +3132,8 @@
 %7D)%0A%0A
-        else:%0A            return Response(serializer.errors)%0A%0A
 %0Acla

update passのインデント修正