package com.kpl.CourierMgmt.CourierManager;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.kpl.CourierMgmt.GoogleMapClient.*;

public class Courier
{
    private IGoogleMapApi mapApi;

    public List<CourierBooking> Schedule;
    public String Name;
    public String InitialLocation;
    public Date TimeAtLocation;
    
    public String GetLocationWhenNextFree()
    {
            if (Schedule == null || Schedule.size() <= 0)
                return InitialLocation;
            else
                return Schedule.get(Schedule.size()-1).GetDestination();
    }

    public Instant GetTimeWhenNextFree() {
    	if(Schedule == null || Schedule.size() == 0)
    		return Instant.now();
    	else
    		return Schedule.get(Schedule.size()-1).GetEstimatedDropOffTime().plus(CourierBooking.DropOffWaitingTime);
    }
       

    public Courier(IGoogleMapApi gma, String name, String location)
    {
    	Schedule = new ArrayList<CourierBooking>();
    	mapApi = gma;
        Name = name;
        InitialLocation = location;
        TimeAtLocation = new Date();
    }

    public Instant CouldArriveAt(IGoogleMapApi mapApi, String location)
    {
        if (GetLocationWhenNextFree().equalsIgnoreCase(location))
            return GetTimeWhenNextFree();

        IGoogleRoute route = mapApi.GetRoute(GetLocationWhenNextFree(), location);
        if (route.GetStatus() == "OK")
            return GetTimeWhenNextFree().plus(route.GetDuration());
        else
            throw new IllegalArgumentException("Route not found: " + route.GetStatus());
    }

    public void TakeBooking(CourierBooking booking)
    {
        IGoogleRoute pickupRoute = mapApi.GetRoute(GetLocationWhenNextFree(), booking.Route.GetOrigin());
        if (pickupRoute.GetStatus() != "OK")
            throw new IllegalArgumentException("Courier unable to take assigned booking");
        booking.EstimatedPickupTime = GetTimeWhenNextFree().plus(pickupRoute.GetDuration());
        booking.PickupRoute = pickupRoute;
        Schedule.add(booking);
    }

    @Override
    public String toString()
    {
        return GetLocationWhenNextFree() + " @ " + GetTimeWhenNextFree();
    }
}
