from django.shortcuts import render
from rest_framework import serializers
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from .serializers import *
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
import requests
from .serializers import CreateUserSerializer

from rest_auth.registration.views import SocialConnectView
from rest_auth.social_serializers import TwitterConnectSerializer

from allauth.socialaccount.providers.twitter.views import TwitterOAuthAdapter
from rest_auth.social_serializers import TwitterLoginSerializer

from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
from rest_auth.registration.views import SocialLoginView

from allauth.socialaccount.providers.oauth2.client import OAuth2Client


# CLIENT_ID = 'CIAE1ipueRIgedYvRk8y9b1TZbPrNCjs4y7QXt55'
# CLIENT_SECRET = 'qEzUVxUlRvgX6ppqziZ6Po3Igxqi9oofyLCQcDz9Dal7BGcSFhQxvKdJoDxXmtpA9WtKIaBj6DMMwsGWj7mZRUvRqzMr0RbQd8JzzdMhBAHdrQNusFFl0BhXNlzzQN3K'
# DOMAIN = 'http://127.0.0.1:8000'


# @api_view(['POST'])
# @permission_classes([AllowAny])
# def register(request):
#     '''
#     Registers user to the server. Input should be in the format:
#     {"username": "username", "password": "1234abcd"}
#     '''
#     # Put the data from the request into the serializer 
#     serializer = CreateUserSerializer(data=request.data) 
#     # Validate the data
#     if serializer.is_valid():
#         # If it is valid, save the data (creates a user).
#         serializer.save() 
#         # Then we get a token for the created user.
#         # This could be done differentley 
#         r = requests.post(DOMAIN+'/o/token/', 
#             data={
#                 'grant_type': 'password',
#                 'username': request.data['username'],
#                 'password': request.data['password'],
#                 'client_id': CLIENT_ID,
#                 'client_secret': CLIENT_SECRET,
#             },
#         )
#         return Response(r.json())
#     return Response(serializer.errors)



# @api_view(['POST'])
# @permission_classes([AllowAny])
# def token(request):
#     '''
#     Gets tokens with username and password. Input should be in the format:
#     {"username": "username", "password": "1234abcd"}
#     '''
#     r = requests.post(
#     DOMAIN+'/o/token/', 
#         data={
#             'grant_type': 'password',
#             'username': request.data['username'],
#             'password': request.data['password'],
#             'client_id': CLIENT_ID,
#             'client_secret': CLIENT_SECRET,
#         },
#     )
#     return Response(r.json())



# @api_view(['POST'])
# @permission_classes([AllowAny])
# def refresh_token(request):
#     '''
#     Registers user to the server. Input should be in the format:
#     {"refresh_token": "<token>"}
#     '''
#     r = requests.post(
#     DOMAIN+'/o/token/', 
#         data={
#             'grant_type': 'refresh_token',
#             'refresh_token': request.data['refresh_token'],
#             'client_id': CLIENT_ID,
#             'client_secret': CLIENT_SECRET,
#         },
#     )
#     return Response(r.json())


# @api_view(['POST'])
# @permission_classes([AllowAny])
# def revoke_token(request):
#     '''
#     Method to revoke tokens.
#     {"token": "<token>"}
#     '''
#     r = requests.post(
#         'http://127.0.0.1:8000/o/revoke_token/', 
#         data={
#             'token': request.data['token'],
#             'client_id': CLIENT_ID,
#             'client_secret': CLIENT_SECRET,
#         },
#     )
#     # If it goes well return sucess message (would be empty otherwise) 
#     if r.status_code == requests.codes.ok:
#         return Response({'message': 'token revoked'}, r.status_code)
#     # Return the error if it goes badly
#     return Response(r.json(), r.status_code)


@api_view(['POST'])
@permission_classes([AllowAny])
def user_exist(request):
    """
    Allows unauthenticated user to checks if a user exist in the system. request = {username: $username} ,  return True/False
    """
    if User.objects.filter(username = request.data['username'],).exists():
        return Response({"exist":"true"}, requests.codes.ok)
    return Response({"exist":"false"}, requests.codes.ok)



class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited
    """
    queryset = User.objects.all()#.order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited
    """
    queryset = Group.objects.all().order_by()
    serializer_class = GroupSerializer



# SOCIAL  ACCOUNT AUTHENTICATION 
class FacebookLogin(SocialLoginView):
    adapter_class = FacebookOAuth2Adapter

class TwitterLogin(SocialLoginView):
    serializer_class = TwitterLoginSerializer
    adapter_class = TwitterOAuthAdapter

class FacebookConnect(SocialConnectView):
    adapter_class = FacebookOAuth2Adapter

class TwitterConnect(SocialConnectView):
    serializer_class = TwitterConnectSerializer
    adapter_class = TwitterOAuthAdapter