import azure.functions as func
import datetime
import json
import urllib.request
import logging

app = func.FunctionApp()


# https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-table?tabs=isolated-process%2Ctable-api%2Cextensionv3&pivots=programming-language-python#output
@app.timer_trigger(
    schedule="*/5 * * * * *",
    arg_name="myTimer",
    run_on_startup=False,
    use_monitor=False,
)
def Timer(myTimer: func.TimerRequest) -> None:
    if myTimer.past_due:
        logging.info("The timer is past due!")
    logging.info("Python timer trigger function executed.")

    endpoint = "https://binghamtonupublic.etaspot.net/service.php?service=get_vehicles&token=TESTING"
    contents = urllib.request.urlopen(endpoint).read()
    try:
        vehicles = json.loads(contents)["get_vehicles"]
        time = datetime.datetime.now()
        seconds = int(
            (time - datetime.datetime(1970, 1, 1)).total_seconds() % (3600 * 24)
        )
        weekday = time.weekday()
        for vehicle in vehicles:
            route = vehicle["routeID"]
            equipment = vehicle["equipmentID"]
            lattitude = vehicle["lat"]
            longitude = vehicle["lng"]
            logging.info(
                f"{route},{equipment},{lattitude},{longitude},{seconds},{weekday}"
            )
    except Exception as e:
        logging.error(e)
        raise e
