#import gtfs_main, 
import time, datetime, requests
import xml.etree.ElementTree as ET
import v
import gtfsloader
from v import *
from countries.sweden import *
from countries.netherlands import *
from countries.denmark import *
from countries.finland import *
from countries.germany import *
from countries.norway import *
from countries.switzerland import *
from countries.france import *
from countries.uk import *
from countries.austria import *

def search(country, operator, station, gtfs_lock):
    try: v.sites[country]
    except: v.sites[country] = {}
    try: v.sites[country][operator]
    except: v.sites[country] = {operator:{}}
    if country == "se":
        if operator == "vt": return vt_lookup(station)
        elif operator == "sj": return sj_lookup(operator, station)
        elif operator == "fe": return ferries_lookup(operator, station)
        elif operator == "sl": return sl_lookup(operator, station)
        elif operator == "norrbotten": return resrobot_lookup(operator, station)
    elif country == "at":
        if operator == "wl": return wl_lookup(operator, station)
    elif country == "de":
        if operator == "db": return db_lookup(operator, station)
        if operator == "kvv": return kvv_lookup(operator, station)
        if operator == "rmv": return rmv_lookup(operator, station)
        if operator == "db_trains": return db_trains_lookup(operator, station)
        if operator == "db2": return db2_lookup(operator, station)
        if operator == "dr": return dr_lookup(operator, station)
        if operator == "be": return be_lookup(operator, station)
        if operator == "kvv": return kvv_lookup(operator, station)
        if operator == "vrr": return vrr_lookup(operator, station)
    elif country == "uk":
        if operator == "lo": return lo_lookup(operator, station)
    elif country == "no":
        return no_lookup(country, operator, station)
        
    elif country == "nl":
        if operator == "ns": return ns_lookup(operator, station, country="nl")
    elif country == "dk":
        if operator == "kb": return kb_lookup(operator, station, country="dk")
        if operator == "dk": return kb_lookup(operator, station, country="dk")
    elif country == "ch":
        
        return ch_zu_lookup(station, operator)
    elif country == "fr":
        if operator == "pa": return pa_lookup(operator, station)
    elif country == "fi":
        if operator == "hsl": return hsl_lookup(operator, station, country="fi")
    #elif operator == "sl": return sl_lookup(operator, station)
    print("TRYING GTFS: ", operator)
    with gtfs_lock: return gtfs_lookup(country, operator, station)
    #return gtfs_lookup(country, operator, station)

def gtfs_lookup(country, operator, station):
    try: v.cache[country]
    except: v.cache[country] = {}
    try: v.cache[country][operator]
    except: 
        v.cache[country][operator] = {"Try again":""}
        gtfsloader.load_static_gtfs(country, operator)
        
    try: data = gtfsloader.search(station, country, operator)
    except Exception as e:
        print(e)
        return {"Try again":""}
    print(data, "DATA!!!")
    if operator == "sncb":
        for result in data:
            data[result] = "S" + data[result]
            #print(result)
            #if result["drop_sum"]: 
            #    print("FOUND")
                #continue
            
    return data
    c=0
    search_list = {}
    for stops in data:
        if "id" in stops:
            if station[:5].lower() in stops["name"].lower():
                    name = stops["name"]
                    id = stops["id"]
                    try: 
                        if name in search_list:
                            print("Double")
                            name = str(name) + " 2"
                    except: pass
                    v.sites[country][operator][name] = id
                    search_list[name] = id
                    c+=1
                    if c > 100: break
    return sort_dict_by_keys(search_list)
        


    return
    search_list = {}
    c = 0
    for stops in data:
        if "id" in stops:
            if station[:5].lower() in stops["name"].lower():
                    name = stops["name"]
                    id = stops["id"]
                    try: 
                        if name in search_list:
                            print("Double")
                            name = str(name) + " 2"
                    except: pass
                    v.sites[country][operator][name] = id
                    search_list[name] = id
                    c+=1
                    if c > 100: break
    return sort_dict_by_keys(search_list)

def gtfs_load_departures(country, station, operator):
    print("Loading GTFS...")
    try: v.cache[country]
    except: v.cache[country] = {}
    try: v.cache[country][operator]
    except: 
        #v.operators[country][operator] = {station:{"departures":[], "message":"Loading...", "timestamp": time.mktime(time.localtime())}}
        gtfsloader.load_static_gtfs(country, operator)
    #gtfsloader.load_static_gtfs(country, operator)
    results = gtfsloader.departure(station, country, operator)
    if operator == "ro":
        for departure in results:
            print(departure)
            if departure["line"]["transport_mode"] == 1: departure["line"]["transport_mode"] = "METRO"
            departure["line"]["id"] = departure["line"]["id"].upper()
    if operator == "nl":
        for departure in results:
            print(departure)
            if departure["line"]["transport_mode"] == 2: departure["line"]["transport_mode"] = "TRAIN"
            departure["line"]["id"] = departure["line"]["id"].upper()
        
    if len(results):
        v.operators[country][operator][station] = {"departures":results, "timestamp": time.mktime(time.localtime())}
        return results
    
    
    return
    try: data = gtfs_main.start_gtfs(country=country, operator=operator, station=station)
    except Exception as e:
        print("Could not download new RT: ", e)
        return
    try:
        for key in data:
            print(key) 
        data = data["departures"]
    except Exception as e:
        print(e)
    print(data)
    results = []
    counter = 0
    for departures in data:
        print(departures)
        #print(departures)
        
        if operator == "sncb":
            if departures["drop_sum"]: continue

        try: _type = departures["type"]
        except: _type = "UNKNOWN"
        #print(departures)
        
        if not "direction" in departures: continue
        destination = departures["direction"].replace(" via ", " v.").replace(" - ", "-")
        if "Endast" in destination: continue

        try: line = (departures["route_short"])
        except: line = "0"
        if "realtime_departure_time" in departures:
            _time = departures["realtime_departure_time"]#[:19]
        #elif "scheduled_departure_time" in departures:
        #    _time = departures["scheduled_departure_time"]#[:19]
        else: continue
        _date = datetime.datetime.now()
        _time = str(_date)[:10] + "T" + str(_time)

        ##########################################################
        if country == "cr" or \
        country == "se" or \
        country == "fr":
        
            if "T0" in _time:
                _time = _time.replace(str(_date.date()), str(_date.date() + datetime.timedelta(days=1)))
        ##########################################################

        else:
            if "T24" in _time: 
                _time = _time.replace("T24","T00")
                _time = _time.replace(str(_date.date()), str(_date.date() + datetime.timedelta(days=1)))
            if "T25" in _time: 
                _time = _time.replace("T25", "T01")
                _time = _time.replace(str(_date.date()), str(_date.date() + datetime.timedelta(days=1)))
            if "T26" in _time: 
                _time = _time.replace("T26", "T02")
                _time = _time.replace(str(_date.date()), str(_date.date() + datetime.timedelta(days=1)))
        
        print(_time)    
        try:
            new_record = {"destination" : destination,
                        "direction_code" : "0",
                        "expected" : _time,
                        "line" : {"id": line.replace("-","."), "transport_mode":_type},
                        "deviations": []}
            results.append(new_record)
        
            
        except: 
            print(v.operators[country][operator])
            print("Error")
    
    if len(results):
        v.operators[country][operator][station] = {"departures":results, "timestamp": time.mktime(time.localtime())}
        return results

try: v.sj_stations = sj_load_stations()
except: pass

vt_client = "MSoM0Zr2or225Nl2NFw7xL3zMToa"
vt_secret = "iHYI8_4fXoyd7VHQf2L28QcGX9Ma"

# UNUSED token = "eyJ4NX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