import requests
from .geocode import Geocode

class Routing:

    def __init__(self):
        self.base_url = "http://router.project-osrm.org/route/v1/"
        self.geo = Geocode()


    def distance(self, origin, destination, mode="driving"):

        o = self.geo.get_coordinates(origin)
        d = self.geo.get_coordinates(destination)

        coords = f"{o['lon']},{o['lat']};{d['lon']},{d['lat']}"

        url = f"{self.base_url}{mode}/{coords}"
        response = requests.get(url)

        data = response.json()
        meters = data["routes"][0]["distance"]
        return meters / 1000


    def route(self, origin, destination, mode="driving"):

        o = self.geo.get_coordinates(origin)
        d = self.geo.get_coordinates(destination)

        coords = f"{o['lon']},{o['lat']};{d['lon']},{d['lat']}"
        url = f"{self.base_url}{mode}/{coords}"
        response = requests.get(url)

        return response.json()


    def travel_time(self, origin, destination):
        data = self.route(origin, destination)
        seconds = data["routes"][0]["duration"]
        return seconds / 60