import json, time, requests
import v
from v import *

def ns_lookup(operator, station, country="nl"):
    station = station.replace(" ", "%20")
    url = "https://gateway.apiportal.ns.nl/nsapp-stations/v3?q=" + station #[?q][&includeNonPlannableStations][&countryCodes][&limit]"
    data = requests.get(url, headers={'accept': 'text/plain', 'Ocp-Apim-Subscription-Key':'84bde7f6d3f94893a31eb6ef63a0cef0'}).text
    
    try: 
        data = json.loads(data)                  
        data = data["payload"]
        search_list = {}
        for stations in data:
            siteid = (stations["id"]["uicCode"])
            name = (stations["names"]["medium"])
            v.sites[country][operator][name] = siteid
            search_list[name] = siteid
        return search_list
    except Exception as e: print("Error: ", e)

def ns_load_departures(station, operator, country="nl"):
    url = "https://gateway.apiportal.ns.nl/reisinformatie-api/api/v2/departures?lang=english&&uicCode=" + station #][&uicCode][&dateTime][&maxJourneys]"
    response = requests.get(url, headers={'accept': 'text/plain', 'Ocp-Apim-Subscription-Key':'84bde7f6d3f94893a31eb6ef63a0cef0'}).text
    departures = json.loads(response)
    departures = departures["payload"]["departures"]
    results = []
    for i in departures:
            destination = i["direction"]
            _time = i["actualDateTime"][:19]
            #try: __line = i["product"]["number"]#[:3]
            #except: __line == "0"
            try: __line = i["plannedTrack"][:3]
            except: __line = "0"
            _canceled = i["cancelled"]
            transport_mode = "TRAIN"
            
            departures_dict = {"destination":destination, 
                               "direction_code":"0",
                               "expected": _time,
                               "line": {"id": __line, "transport_mode":transport_mode},
                               "deviations":[]}
            if not _canceled: results.append(departures_dict)
    
    if len(results):
        v.operators[country][operator][station] = {"departures" : results, "timestamp" : time.mktime(time.localtime())}
        return results

# Testa sök station: 'amsterdam'
#ns_lookup("ns", "amsterdam")

# Testa hämta avgångar: '8400319'
#ns_load_departures("8400319", "ns")
