import random
from django.shortcuts import render
from rest_framework import status
from django.http import JsonResponse
from datetime import datetime, timedelta
from django.views.decorators.csrf import csrf_exempt
import json
from DRIVERZZ_ADMIN_APIS import settings
from authentication.auth import verify_token


from rates.models import Daytimes, RateLists
from trips.helpers import calculate_fare, calculate_estimated_fare, create_order, total_daytime_minutes, calculate_taxes

from .models import Trips
from .serializers import TripSerializer, TripsSerializer
from authentication.models import User


@csrf_exempt
def trips(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message' : "User 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)

            try:
                user = User.objects.get(mobile = request_data['mobile'])
            except User.DoesNotExist:
                user = User()
                user.mobile = request_data['mobile']
                user.is_active = 1
                user.is_staff = 0
                user.is_superuser = 0
                username = ''.join((random.choice('1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(6)))
                user.username = 'USER-' + username
                user.user_type = 2
                user.save()

            trip = Trips()
            trip.user_id = user.id
            trip.vehicle_model_id = request_data['vehicle_model_id']
            trip.vehicle_type_id = request_data['vehicle_type_id']
            trip.transmission_type_id = request_data['transmission_type_id']
            trip.vehicle_model_name = request_data['vehicle_model_name']
            trip.vehicle_type_name = request_data['vehicle_type_name']
            trip.transmission_type_name = request_data['transmission_type_name']
            trip.trip_type = int(request_data['trip_type'])
            trip.station_type = int(request_data['station_type'])
            trip.pickup_address = request_data['pickup_address']
            trip.pickup_latitude = request_data['pickup_latitude']
            trip.pickup_longitude = request_data['pickup_longitude']
            trip.destination_address = request_data['destination_address']
            trip.destination_latitude = request_data['destination_latitude']
            trip.destination_longitude = request_data['destination_longitude']
            trip.start_date = request_data['start_date']
            trip.end_date = request_data['end_date']
            trip.start_time = request_data['start_time']
            trip.end_time = request_data['end_time']
            trip.uniform_type = request_data['uniform_type']
            trip.instructions = request_data['instructions']
            trip.amount = int(calculate_estimated_fare(trip))
            trip.net_amount = int(calculate_taxes(trip.amount))  
            trip.save()
            return JsonResponse({'message': "Trip Created successfully",'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        else:
            trip = Trips.objects.all().order_by('-id')
            serializer = TripsSerializer(trip, many=True)
            return JsonResponse({'trips' : serializer.data, 'status':status.HTTP_200_OK},safe=False, status=status.HTTP_200_OK)



@csrf_exempt
def editTrip(request):  
    if request.method == 'GET':
        try:
            trip = Trips.objects.get(id = request.GET.get('id'))
            serializer = TripSerializer(trip, many = False)
            return JsonResponse({'trip': serializer.data,'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        except Trips.DoesNotExist:
            return JsonResponse({'message': "Invalid trip id.",'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
        except Exception as 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) 

    else:
        try:
            request_data = json.loads(request.body)
            trip = Trips.objects.get(id = request_data['id'])
            trip.vehicle_model_id = request_data['vehicle_model_id']
            trip.vehicle_type_id = request_data['vehicle_type_id']
            trip.transmission_type_id = request_data['transmission_type_id']
            trip.vehicle_model_name = request_data['vehicle_model_name']
            trip.vehicle_type_name = request_data['vehicle_type_name']
            trip.transmission_type_name = request_data['transmission_type_name']
            trip.trip_type = int(request_data['trip_type'])
            trip.pickup_address = request_data['pickup_address']
            trip.pickup_latitude = request_data['pickup_latitude']
            trip.pickup_longitude = request_data['pickup_longitude']
            trip.destination_address = request_data['destination_address']
            trip.destination_latitude = request_data['destination_latitude']
            trip.destination_longitude = request_data['destination_longitude']
            trip.trip_start_date = request_data['start_date']
            trip.trip_end_date = request_data['end_date']
            trip.trip_start_time = request_data['start_time']
            trip.trip_end_time = request_data['end_time']
            trip.instructions = request_data['instructions']  
            trip.amount = int(calculate_fare(trip))
            trip.net_amount = int(calculate_taxes(trip.amount))
            trip.save()
            return JsonResponse({'message': "Trip Edited successfully",'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
        except Trips.DoesNotExist:
            return JsonResponse({'message': "Invalid trip id.",'status':status.HTTP_400_BAD_REQUEST}, safe=False, status=status.HTTP_400_BAD_REQUEST)
        except Exception as 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 assignTrip(request):
    user_id = verify_token(request)
    if user_id == None:
        return JsonResponse({'message' : "User not login", 'status':status.HTTP_401_UNAUTHORIZED}, safe=False, status=status.HTTP_401_UNAUTHORIZED)
    else:
        request_data = json.loads(request.body)
        trip = Trips.objects.get(id = request_data['trip'])
        trip.status = 1
        trip.driver_id = request_data['driver']
        trip.save()
        return JsonResponse({'message': "Trip assigned successfully",'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)



@csrf_exempt
def changeTripStatus(request):
    try:
        user_id = verify_token(request)
        if user_id == None:
            return JsonResponse({'message' : "User not login", 'status':status.HTTP_401_UNAUTHORIZED}, safe=False, status=status.HTTP_401_UNAUTHORIZED)
        else:
            request_data = json.loads(request.body)
            trip = Trips.objects.get(id = request_data['trip'])
            trip.status = request_data['status']
            # trip.save()
            if request_data['status'] == 3:
                trip.trip_start_date = datetime.now().date()
                trip.trip_start_time = datetime.now().time().strftime("%I:%M %p")
                # trip.amount = int(calculate_fare(trip))
                # trip.net_amount = int(calculate_taxes(trip.amount))
                
            elif request_data['status'] == 4:
                trip.trip_end_date = datetime.now().date()
                trip.trip_end_time = datetime.now().time().strftime("%I:%M %p")
                trip.amount = int(calculate_fare(trip))
                trip.net_amount = int(calculate_taxes(trip.amount))
                trip.reference_id = create_order(trip)
                
            trip.save()
            return JsonResponse({'message': "Trip status changed successfully",'status':status.HTTP_200_OK}, safe=False, status=status.HTTP_200_OK)
    except Exception as e:
        print(e)