import random
from django.shortcuts import render
from rest_framework import status
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.hashers import check_password, make_password
import json

from authentication.auth import verify_token
from authentication.models import User
from driver_partners.serializer import DriverPartnerSerializer, DriverPartnerListSerializer
from .models import DriverPartners, DriverVehicles



@csrf_exempt
def driverPartners(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message' : "User is not login", 'status':status.HTTP_401_UNAUTHORIZED}, safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        if request.method == 'POST':
            request_data = json.loads(request.body)
            user = User()

            user.name = request_data['name']
            user.email = request_data['email']
            user.mobile = request_data['mobile']
            user.password = make_password('123456')
            user.user_type = 3
            user.is_staff = 1
            user.is_active = request_data['status']
            username = ''.join((random.choice('1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(6)))
            user.username = 'USER-' + username
            user.is_superuser = 0
            user.save()

            if user.id:
                driver_partner = DriverPartners()
                driver_partner.user_id = user.id
                driver_partner.gender = int(request_data['gender'])
                driver_partner.licensce_no = request_data['licensce_no']
                driver_partner.date_of_birth = request_data['date_of_birth']
                driver_partner.experience = request_data['experience']
                driver_partner.location = request_data['location']
                driver_partner.house_number = request_data['house_number']
                driver_partner.pincode = request_data['pincode']
                driver_partner.uniform_type = int(request_data['uniform_type'])
                driver_partner.station_type = int(request_data['station_type'])
                driver_partner.trip_type = int(request_data['trip_type'])
                driver_partner.transmission_type =  int(request_data['transmission_type'])
                driver_partner.save()

                if request_data['vehicle_models']:
                    DriverVehicles.objects.bulk_create([
                        DriverVehicles(driver_id = user.id,  vehicle_model = vehicle_model) for vehicle_model in request_data['vehicle_models']
                    ])

                return JsonResponse({'message' : "Driver partner added Succesfully", '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)
        
        else:
            driver_partner = DriverPartners.objects.all()
            serializer = DriverPartnerSerializer(driver_partner, many=True)
            return JsonResponse({'driver_partners': serializer.data, 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        
        

def driverPartnersList(request):
    driver_partner = DriverPartners.objects.all()
    serializer = DriverPartnerListSerializer(driver_partner, many=True)
    return JsonResponse({'driver_partners': serializer.data, 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)

    
@csrf_exempt     
def editDriverPartner(request):
    if request.method == 'POST':
        request_data = json.loads(request.body)
        if request_data['id']:
            driver_partner = DriverPartners.objects.get(id=request_data['id'])
            driver_partner.user.name = request_data['name']
            driver_partner.user.mobile = request_data['mobile']
            driver_partner.user.email = request_data['email']
            driver_partner.user.is_active = int(request_data['status'])
            
            driver_partner.gender = int(request_data['gender'])
            driver_partner.licensce_no = request_data['licensce_no']
            driver_partner.date_of_birth = request_data['date_of_birth']
            driver_partner.experience = request_data['experience']
            driver_partner.location = request_data['location']
            driver_partner.house_number = request_data['house_number']
            driver_partner.pincode = request_data['pincode']
            driver_partner.uniform_type = int(request_data['uniform_type'])
            driver_partner.station_type = int(request_data['station_type'])
            driver_partner.trip_type = int(request_data['trip_type'])
            driver_partner.transmission_type =  int(request_data['transmission_type'])
            driver_partner.user.save()
            driver_partner.save()

            DriverVehicles.objects.filter(driver_id = driver_partner.user.id).delete()
            if request_data['vehicle_models']:
                DriverVehicles.objects.bulk_create([
                    DriverVehicles(driver_id = driver_partner.user.id,  vehicle_model = vehicle_model) for vehicle_model in request_data['vehicle_models']
                ])
            return JsonResponse({'message' : "Driver details edited Succesfully", 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        else:
            return JsonResponse({'message':"Driver id is required", 'status': status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
    
    else:
        if request.GET.get('id'):
            try:
                driver_partner = DriverPartners.objects.get(id=request.GET.get('id'))
                serializer = DriverPartnerSerializer(driver_partner, many=False)
                return JsonResponse({'driver_partner': serializer.data, 'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
            except DriverPartners.DoesNotExist:
                return JsonResponse({'message':"Driver partner doesn't exists.", 'status': status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
        else:
            return JsonResponse({'message':"Driver partner id is required", 'status': status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)