o
    Ѳ]f                     @   s   d dl mZ d dlmZ d dlmZ d dlmZ ddlm	Z	 ddl
T d dlmZ d d	lmZ d d
lZd dlmZ d dlmZmZ d d
lZdd Zdd Zedd Zdd Zd
S )    )timezone)	timedelta)Distance)DriverLocation   )Ride)*)sync_to_async)DecimalN)ValidationError)r
   ROUND_UPc                 C   s   d}|  d| }| d| }d| d| d| }t |}| }	|	d dkr0t|	d tt|	d	 d
 d d
 d d d }
|
S )Nz'AIzaSyAEWPwKw_tv81JSa0x_glii-pz51JCX_PU,zAhttps://maps.googleapis.com/maps/api/distancematrix/json?origins=z&destinations=z&key=statusOKerror_messagerowsr   elementsdistancevaluei  )requestsgetjsonr   r
   str)from_latitudefrom_longitudeto_latitudeto_longitudeapi_keyoriginsdestinationsendpointresponsedatadistance_in_km r$   %/var/www/html/loop/booking/process.pycalculate_distance   s   
"r&   c                 O   sJ   zt  }W n ty   t  }t | Y nw || |i | d S )N)asyncioget_running_loopRuntimeErrornew_event_loopset_event_loopcreate_task)
async_funcargskwargsloopr$   r$   r%   setup_async_tasks    s   r1   c                 C   s   t d t tdd }t d || j  kr!|tdd krtn nQt d t| j| j}t d t| jj	| jj
| jj	| jj
}|| jj }|jtdtd	}|| _|| _|   |rrt d
 t||  t d d| _|   d S d S t d d S )Nz>Step 1: Adjusting current time to account for potential delays   )minutesz?Step 2: Checking if the ride time is within the next 15 minutes   zAStep 3: Finding the nearest available driver for the vehicle typez/Step 4: Calculating distance and estimated farez0.01)roundingzBStep 6: Sending a notification to the driver with the ride detailsz0Step 7: Updating the ride status to 'processing'
processingz0The ride time is not within the next 15 minutes.)printr   nowr   	ride_timefind_nearest_available_driverpickup_locationvehicle_typer&   yxdropoff_locationper_km_chargequantizer
   r   r   estimated_faresavenotify_driver_new_rider   )rideadjusted_current_timenearest_driverr   rB   rounded_farer$   r$   r%   process_new_ride)   s@   

rI   c                 C   s6   t jjd|ddjtd| dd}|r| S d S )NFT)"driver__assigned_vehicles__on_ride0driver__assigned_vehicles__vehicle__vehicle_type!driver__assigned_vehicles__activelast_known_location)r   r   )r   objectsfilterannotater   order_byfirst)r;   r<   available_driversr$   r$   r%   r:   O   s   
	r:   )django.utilsr   datetimer   &django.contrib.gis.db.models.functionsr   accounts.modelsr   modelsr   notificationsasgiref.syncr	   decimalr
   r   rest_framework.exceptionsr   r   r'   r&   r1   rI   r:   r$   r$   r$   r%   <module>   s"    	
%