import json
import random
from django.http import JsonResponse
from django.shortcuts import render
from rest_framework import status
from django.views.decorators.csrf import csrf_exempt

from DRIVERZZ_DRIVER_APIS import settings
from .helpers import send_otp_to_phone
from .auth import generate_access_token, verify_token
from .models import DriverPartners, DriverVehicles, User
from .serializers import DriverSerializer

# Create your views here.

@csrf_exempt
def requestOtp(request):
    try:
        request_data = json.loads(request.body)
        user = User.objects.get(mobile = request_data['mobile'], user_type = 3)
        otp = ''.join((random.choice('1234567890') for i in range(4)))
        otp = "1234"
        response = send_otp_to_phone(request_data['mobile'], otp)
        if response:
            request.session['otp'] = otp
            request.session['mobile'] = request_data['mobile']
            return JsonResponse({'message' : "OTP sent to registered Mobile", 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        else:
            return JsonResponse({'message' : "Something went wrong. Please try again later.", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
    except User.DoesNotExist:
        return JsonResponse({'message' : "Mobile no. doesn't exists", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
    except Exception as e:
        print(e)
        return JsonResponse({'message' : "Something went wrong. Please try again later.", 'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)


@csrf_exempt
def verifyOtp(request):
    request_data = json.loads(request.body)        
    otp = request_data['otp']
    if(otp == request.session['otp']):
        try:
            user = User.objects.get(mobile = request.session['mobile'])
            token = generate_access_token(user)
            return JsonResponse({'message': "Otp Matched successfully", 'token' : token, 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)    
        except User.DoesNotExist:
            return JsonResponse({'message': "User doesn't exists.",'status':status.HTTP_400_BAD_REQUEST},safe=False, status=status.HTTP_400_BAD_REQUEST)
    else:
        return JsonResponse({'message': "Otp not Matched",'status':status.HTTP_400_BAD_REQUEST},safe=False, status=status.HTTP_400_BAD_REQUEST)
          

def showDelete(request):
    return JsonResponse({'show_delete' : settings.SHOW_DELETE, 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)


@csrf_exempt  
def deleteAccount(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED},  safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        try:
            User.objects.get(id = user_id).delete()
        except Exception as e:
            print(e)
        return JsonResponse({'message' : "Account deleted successfully.", 'status':status.HTTP_200_OK},  safe=False, status=status.HTTP_200_OK)


@csrf_exempt
def verifyUser(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED},  safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        try:
            user = User.objects.get(id = user_id)
            return JsonResponse({'message' : "user is verified.", 'name' : user.name, 'email' : user.email, 'mobile' : user.mobile, 'status':status.HTTP_200_OK},  safe=False, status=status.HTTP_200_OK)
        except User.DoesNotExist:
            return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED},  safe=False, status=status.HTTP_401_UNAUTHORIZED)
        


@csrf_exempt
def profile(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED},  safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        try:
            driver = DriverPartners.objects.get(user_id = user_id)
            serializer = DriverSerializer(driver, many=False)
            return JsonResponse({'driver' : serializer.data, 'message' : "Profile updated successfully.", 'status':status.HTTP_200_OK},  safe=False, status=status.HTTP_200_OK)
        except User.DoesNotExist:
            return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED},  safe=False, status=status.HTTP_401_UNAUTHORIZED)
        





@csrf_exempt
def basicInfo(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED},  safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        try:
            driver = DriverPartners.objects.get(user_id = user_id)
            driver.user.name = request.POST.get('name')
            driver.user.mobile = request.POST.get('mobile')
            driver.user.email = request.POST.get('email')
            driver.gender = request.POST.get('gender')
            driver.experience = request.POST.get('experience') 
            if 'profile_pic' in request.FILES:
                driver.user.profile_pic = request.FILES.get('profile_pic')
            driver.save()
            driver.user.save()
            return JsonResponse({'message' : "Basic info updated successfully.", 'status':status.HTTP_200_OK},  safe=False, status=status.HTTP_200_OK)
        except User.DoesNotExist:
            return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED},  safe=False, status=status.HTTP_401_UNAUTHORIZED)
        


@csrf_exempt
def addressInfo(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED},  safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        try:
            request_data = json.loads(request.body)
            driver = DriverPartners.objects.get(user_id = user_id)
            driver.location = request_data['location']
            driver.house_number = request_data['house_number']
            driver.pincode = request_data['pincode']
            driver.save()
            return JsonResponse({'message' : "Address updated successfully.", 'status':status.HTTP_200_OK},  safe=False, status=status.HTTP_200_OK)
        except User.DoesNotExist:
            return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED},  safe=False, status=status.HTTP_401_UNAUTHORIZED)
        


@csrf_exempt
def prefrences(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED},  safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        try:
            request_data = json.loads(request.body)
            driver = DriverPartners.objects.get(user_id = user_id)
            driver.uniform_type = request_data['uniform_type']
            driver.trip_type = request_data['trip_type']
            driver.station_type = request_data['station_type']
            driver.transmission_type = request_data['transmission_type']
            driver.save()
            DriverVehicles.objects.filter(driver_id = driver.user_id).delete()
            if request_data['vehicle_models']:
                DriverVehicles.objects.bulk_create([
                    DriverVehicles(driver_id = driver.user_id,  vehicle_model = vehicle_model) for vehicle_model in request_data['vehicle_models']
                ])
            return JsonResponse({'message' : "Address updated successfully.", 'status':status.HTTP_200_OK},  safe=False, status=status.HTTP_200_OK)
        except User.DoesNotExist:
            return JsonResponse({'message' : "User not logged in.", 'status':status.HTTP_401_UNAUTHORIZED},  safe=False, status=status.HTTP_401_UNAUTHORIZED)
        
