from datetime import datetime, time, timedelta
import random

from DRIVERZZ_ADMIN_APIS import settings
from rates.models import Daytimes, RateLists, Taxes
import razorpay


def calculate_fare(trip):
    try:
        amount = 0
        start_time = datetime.strptime(trip.trip_start_time, '%I:%M %p').time()
        start_timestamp = datetime.strptime(str(trip.trip_start_date)+" "+str(start_time), '%Y-%m-%d %H:%M:%S')
        if trip.status == 2:
            end_time = datetime.strptime(trip.end_time, '%I:%M %p').time()
            end_timestamp = datetime.strptime(str(trip.end_date)+" "+str(end_time), '%Y-%m-%d %H:%M:%S')
        else:
            end_time = datetime.strptime(trip.trip_end_time, '%I:%M %p').time()
            end_timestamp = datetime.strptime(str(trip.trip_end_date)+" "+str(end_time), '%Y-%m-%d %H:%M:%S')
        

        time_delta = end_timestamp - start_timestamp
        total_minutes = int((time_delta.total_seconds())/60)

        if total_minutes >= 120:
            pass
        else:
            extra_minutes = 120-total_minutes
            end_timestamp = end_timestamp + timedelta(minutes=extra_minutes)
            time_delta = end_timestamp - start_timestamp
            total_minutes = int((time_delta.total_seconds())/60)

        rate_day = RateLists.objects.filter(duration__gte=total_minutes, station_type = trip.station_type, day = 0, trip_type = trip.trip_type).order_by('duration')
        rate_night = RateLists.objects.filter(duration__gte=total_minutes, station_type = trip.station_type, day = 1, trip_type = trip.trip_type).order_by('duration')
        
        if(len(rate_day) == 0):
            rate_day = RateLists.objects.filter(duration__lt=total_minutes, station_type = trip.station_type, day = 0, trip_type = trip.trip_type).order_by('-duration')
            rate_night = RateLists.objects.filter(duration__lt=total_minutes, station_type = trip.station_type, day = 1, trip_type = trip.trip_type).order_by('-duration')
        
        day_charges = rate_day[0].rate
        night_charges = rate_night[0].rate

        print("day charge : " + str(day_charges))
        print("night charge : " + str(night_charges))
        
        day = Daytimes.objects.get(day_type = 0)
        day_start = datetime.strptime(day.start_time, '%I:%M %p').time()

        day = Daytimes.objects.get(day_type = 1)
        day_end = datetime.strptime(day.start_time, '%I:%M %p').time()

        day_minutes = 0
        night_minutes = 0

        day_start = (day_start.hour, day_start.minute)
        day_end = (day_end.hour, day_end.minute)

        day_minutes = total_daytime_minutes(day_start, day_end, start_timestamp, end_timestamp)


        if start_timestamp.date() == end_timestamp.date():
            day_minutes = day_minutes / 2 


       

        night_minutes = total_minutes - day_minutes
        print("total_minutes : "+ str(total_minutes))
        print("day_minutes : "+ str(day_minutes))
        print("night_minutes : "+ str(night_minutes))

        amount += day_minutes * day_charges
        
        amount += night_minutes * night_charges

        print("total_amount : "+ str(amount))
        return amount
    except Exception as e:
        print(e)




def calculate_estimated_fare(trip):
    amount = 0
    start_time = datetime.strptime(trip.start_time, '%I:%M %p').time()
    start_timestamp = datetime.strptime(str(trip.start_date)+" "+str(start_time), '%Y-%m-%d %H:%M:%S')
    
    end_time = datetime.strptime(trip.end_time, '%I:%M %p').time()
    end_timestamp = datetime.strptime(str(trip.end_date)+" "+str(end_time), '%Y-%m-%d %H:%M:%S')
   
    time_delta = end_timestamp - start_timestamp
    total_minutes = int((time_delta.total_seconds())/60)

    if total_minutes >= 120:
        pass
    else:
        extra_minutes = 120-total_minutes
        end_timestamp = end_timestamp + timedelta(minutes=extra_minutes)
        time_delta = end_timestamp - start_timestamp
        total_minutes = int((time_delta.total_seconds())/60)

    rate_day = RateLists.objects.filter(duration__gte=total_minutes, station_type = trip.station_type, uniform_type = trip.uniform_type, day = 0, trip_type = trip.trip_type).order_by('duration')
    rate_night = RateLists.objects.filter(duration__gte=total_minutes, station_type = trip.station_type, uniform_type = trip.uniform_type, day = 1, trip_type = trip.trip_type).order_by('duration')
            
    if(len(rate_day) == 0):
        rate_day = RateLists.objects.filter(duration__lt=total_minutes, station_type = trip.station_type, uniform_type =  trip.uniform_type, day = 0, trip_type = trip.trip_type).order_by('-duration')
        rate_night = RateLists.objects.filter(duration__lt=total_minutes, station_type = trip.station_type, uniform_type =  trip.uniform_type, day = 1, trip_type = trip.trip_type).order_by('-duration')
    
    day_charges = rate_day[0].rate
    night_charges = rate_night[0].rate
    
    day = Daytimes.objects.get(day_type = 0)
    day_start = datetime.strptime(day.start_time, '%I:%M %p').time()


    day = Daytimes.objects.get(day_type = 1)
    day_end = datetime.strptime(day.start_time, '%I:%M %p').time()

    day_minutes = 0
    night_minutes = 0

    day_start = (day_start.hour, day_start.minute)
    day_end = (day_end.hour, day_end.minute)

    day_minutes = total_daytime_minutes(day_start, day_end, start_timestamp, end_timestamp)


    if start_timestamp.date() == end_timestamp.date():
        day_minutes = day_minutes / 2 


    night_minutes = total_minutes - day_minutes

    amount += day_minutes * day_charges
    
    amount += night_minutes * night_charges
    print(amount)
    return amount




def calculate_taxes(amount):
    trip_amount = amount
    taxes = Taxes.objects.all()
    for tax in taxes:
        trip_amount = float(trip_amount + float(amount * float(tax.tax_percentage) / 100))
    return trip_amount



def total_daytime_minutes(start_time, end_time, datetime1, datetime2):
    # Extract date part from datetime objects
    
    date1 = datetime1.date()
    date2 = datetime2.date()

   
    # Define start and end time as time objects
    start_time_obj = time(*start_time)
    end_time_obj = time(*end_time)

    # Create datetime objects with defined times for comparison
    day_start1 = datetime.combine(date1, start_time_obj)
    day_end1 = datetime.combine(date1, end_time_obj)
    day_start2 = datetime.combine(date2, start_time_obj)
    day_end2 = datetime.combine(date2, end_time_obj)

    # Calculate total daytime in minutes
    total_minutes = 0

    if datetime1 <= day_end1 and datetime2 >= day_start1:
        # Calculate overlap duration
        overlap_start = max(datetime1, day_start1)
        overlap_end = min(datetime2, day_end1)
        overlap_duration = (overlap_end - overlap_start).total_seconds() / 60
        total_minutes += max(0, overlap_duration)

    if datetime1 <= day_end2 and datetime2 >= day_start2:
        # Calculate overlap duration
        overlap_start = max(datetime1, day_start2)
        overlap_end = min(datetime2, day_end2)
        overlap_duration = (overlap_end - overlap_start).total_seconds() / 60
        total_minutes += max(0, overlap_duration)

    return total_minutes
    



def create_order(trip):
    razorpay_client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_KEY_SECRET))
    reference_id  = ''.join((random.choice('abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(8)))
    reference_id = '#' + reference_id 
    razorpay_client.payment_link.create({
        "amount": trip.net_amount * 100,
        "currency": "INR",
        "accept_partial": False,
        "reference_id" : reference_id,
        "customer": {
            "name": "",
            "email": "",
            "contact": "+91" + str(trip.user.mobile)
        },
        "notify": {
            "sms": True,
        },
        "options": {
            "checkout": {
                "method": {
                    "netbanking": True,
                    "card": True,
                    "upi": True,
                    "wallet": False,
                    "paylater" : False
                }
            }
        },
        "callback_url": settings.RAZORPAY_CALLBACK_URL,
        "callback_method": "get"
    })

    return reference_id