import firebase_admin
from firebase_admin import messaging,credentials

cred = credentials.Certificate('loop-com-firebase-adminsdk-1giu3-8a1c208390.json')
firebase_admin.initialize_app(cred)


def notify_user_driver_arrived(user, ride):
    title = "Driver Has Arrived"
    body = "Your driver has arrived at the pickup location."
    device_token = user.devices.first().device_token
    send_firebase_notification(device_token, title, body)

def notify_user_ride_started(user, ride):
    title = "Ride Started"
    body = "Your ride has started. Enjoy your journey!"
    device_token = user.devices.first().device_token
    send_firebase_notification(device_token, title, body)

def notify_user_ride_finished(user, ride):
    title = "Ride Finished"
    body = "Your ride has finished. Thank you for using our service!"
    device_token = user.devices.first().device_token
    send_firebase_notification(device_token, title, body)

def notify_user_driver_reaching(user, ride):
    title = "Driver is Approaching"
    body = "Your driver is almost there. Please be ready for pickup."
    device_token = user.devices.first().device_token
    send_firebase_notification(device_token, title, body)


def notify_user_ride_accepted(user, ride):
    title = "Ride Accepted"
    body = f"Your ride has been accepted."
    device_token = user.devices.first().device_token
    data = {'ride_id':str(ride.id)}
    send_firebase_notification(device_token, title, body,data)

def notify_driver_new_ride(driver_location, ride):
    print("Step 1: Constructing notification details")
    title = "New Ride Request"
    body = "You have a new ride request."
    data = {
        'ride_id': str(ride.id),
        'pickup_coords': str(ride.pickup_location.coords),
        'dropoff_coords': str(ride.dropoff_location.coords)
    }
    print("Step 2: Retrieving driver's device token")
    driver = driver_location.driver
    device_token = driver.devices.first().device_token
    print("Step 3: Sending Firebase notification to driver")
    send_firebase_notification(device_token, title, body, data)




def send_firebase_notification(device_token, title, body, data=None):
    # Create the message
    message = messaging.Message(
        notification=messaging.Notification(
            title=title,
            body=body,
        ),
        data=data,
        token=device_token,
    )

    # Send the message via FCM
    response = messaging.send(message)
    return response
