
import json

from django.contrib.auth import get_user_model
import requests
from rest_framework import serializers, status, permissions, parsers, renderers
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.serializers import AuthTokenSerializer
from rest_framework.response import Response
from rest_framework.views import APIView

from config import URL_JAMESPOT
from ammico.views import populateVisit


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()

class User(APIView):
    """
    get list user or add user
    """
    permission_classes = (permissions.AllowAny,)
    
    def get(self, request):
        print ("here ?")
        user = get_user_model().objects.all()
        serializer = UserSerializer(user, many=True)
        return Response(serializer.data)
        
    def post(self, request):
        VALID_USER_FIELDS = [f.name for f in get_user_model()._meta.fields]
        DEFAULTS = {
            "groups":"",
            "user_permissions":""
        }
        request.data.update(DEFAULTS)
        serialized = UserSerializer(data=request.data)
        
        if serialized.is_valid():
            user_data = {field: data for (field, data) in request.DATA.items() if field in VALID_USER_FIELDS}
            
            params = {'o': 'user', 'f': 'get', 'mail': user_data['email']}
            r = requests.get(URL_JAMESPOT, params=params)
            infoUser = json.loads(r.content.decode('utf-8'))
            if ('idUser' in infoUser['VAL']):
                user_data.update({"idUser":infoUser['VAL']['idUser']})
            user = get_user_model().objects.create_user(
                **user_data
            )
            return Response(UserSerializer(instance=user).data, status=status.HTTP_201_CREATED)
        else:
            return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
        
class ObtainAuthToken(APIView):
    throttle_classes = ()
    permission_classes = ()
    parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
    renderer_classes = (renderers.JSONRenderer,)

    def post(self, request):
        serializer = AuthTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        if (user.idUser):
            populateVisit(user)
        token, created = Token.objects.get_or_create(user=user)
        return Response({'token': token.key})