
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.response import Response
from rest_framework.views import APIView

from ammico.views import populateVisit
from django.conf import settings


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):
        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]
        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(settings.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):
        user = get_user_model().objects.get(email = request.data['email'], password = request.data['password'])
        if (user.idUser):
            populateVisit(user)
        token, _ = Token.objects.get_or_create(user=user)
        return Response({'token': token.key})
