# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/distance.ipynb (unless otherwise specified).

__all__ = ['getDistanceOsrm', 'getDistBing']

# Cell
from beartype import beartype
from typing import List, Dict, Tuple
import pandas as pd
import yaml, requests

# Cell
@beartype
def getDistanceOsrm(lat1:float, lon1:float, lat2:float, lon2:float,
                    osrmEndpoint = 'http://router.project-osrm.org')->float:
  '''
    get driving distance between 2 points using osrm url
  '''
  url = f"{osrmEndpoint}/route/v1/bike/{lon1},{lat1};{lon2},{lat2}?overview=false"
  r = requests.get(url)
  try:
    distance = r.json()['routes'][0]['distance']
    return float(distance)
  except KeyError as e:
    raise KeyError(f"error getting distance got {r.json()} from urll \n{e}")


# Cell
@beartype
def getDistBing(origin:Tuple[float,float]
                ,destinations:List[Tuple[float,float]],
                 bingApiKey:str = '')->pd.DataFrame:
  '''
    accept a list of tuple origins and destinations, return a dataframe
    input:
      origin :: Tuple[float,float] : (lat,long) of the origin
      destinations:: List[Tuple[float,float]]: [(lat,long),(lat,long)] of the destinations
      bingApiKey:str:: apikey from bing map
    response:
      pd.DataFrame with [dist, dur, lat, long] as indexes, all in float,
          all distances in m and time in s
  '''

  parameters = {
    'origins' : f'{origin[0]},{origin[1]}',
    'destinations' : ';'.join(f'{d[0]},{d[1]}'for d in destinations),
    'travelMode' : 'driving',
    'key': bingApiKey
  }
  url = 'https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix'
  r =  requests.get(url,params=parameters).json()
  results:pd.DataFrame = pd.DataFrame(r['resourceSets'][0]['resources'][0]['results'])
  destinationsDf:pd.DataFrame = pd.DataFrame(destinations)
  destinationsDf.columns = ['lat', 'long']
  results = pd.concat([results,destinationsDf],axis=1).reindex(
    ['travelDistance','travelDuration', 'lat','long'], axis = 1)
  results.columns  = ['dist', 'dur', 'lat', 'long']
  return results
