import v
from v import *

def kb_load_departures(station, operator, country="dk"):
    def load_cycle(x, load_type):
        #x = "&time=" + str(datetime.datetime.now())[11:16]
        
        
        
        search_list = {}
        results = []
        
        #print(x)
        #import sys; sys.exit()
        for departures in x["Departure"]:
            
            #for i in departures:
                try:
                    #try: print(departures["name"])
                    #except: pass
                    __type = departures["ProductAtStop"]["catOutL"].lower()
                    print(__type)
                    try: 
                        line = departures["ProductAtStop"]["line"]
                        id = departures["ProductAtStop"]["line"]
                    except: 
                        line = departures["ProductAtStop"]["operatorInfo"]["name"]
                        id = departures["ProductAtStop"]["operatorInfo"]["name"]
                        print(departures["ProductAtStop"]["operatorInfo"]["name"])
                        
                    
                    
                    name = departures["direction"]
                    _date = departures["date"]
                    
                    try: _time = departures["rtTime"]
                    except: _time = departures["time"]
                    
                    
                    
                    __date = _date#datetime.datetime.strptime(_date, '%d-%m-%y').strftime('%Y-%m-%d')
                    ___date = __date + "T" + _time + ":00"
                    #print(___date)
                    _time = ___date
                    
                    
                    if __type == "m": __type = "metro"
                    elif __type == "regional": __type = "train"
                    elif __type == "re": __type = "train"
                    elif __type == "metro": __type = "metro"
                    elif __type == "express": __type = "train"
                    elif __type == "lyn": __type = "train"
                    elif __type == "reg": __type = "train"
                    elif __type == "ic": __type = "train"
                    elif __type == "s-tog": __type = "train"
                    elif __type == "tog": __type = "train"
                    elif __type == "exb": __type = "bus"
                    elif __type == "nb": __type = "bus"
                    elif __type == "tb": __type = "bus"
                    elif __type == "f": __type = "ship"
                    elif __type == "let": __type = "tram"
                    elif __type == "hv-bus": __type = "bus"
                    elif "bus" in __type: __type = "bus"
                    elif "ic" in __type: __type = "train"
                    elif "letbane" in __type: __type = "tram"

                    
                    #print(__type)

                    new_record = {"destination" : name.replace("via ", ""),
                                "direction_code" : "0",
                                "expected" : _time[:19],
                                "line" : {"id": line.replace("-","."),
                                "transport_mode":__type.upper()},
                                "deviations": [],
                                "id": id,}
                    results.append(new_record)
                    
                except Exception as e: 
                    print("Error: ", e)
                    continue


        if len(results):
            v.operators[country][operator][station]["departures"] = results
            return results
            print("Success")
        
    all_types = "&useMetro=0&useBus=0&useTog=0"
    #cycle_list =  {"Metro=0":"Metro=1", "Tog=0":"Tog=1", "Bus=0":"Bus=1"}
    cycle_list =  {"Metro=0":"Metro=1"}
    results = []
    data = requests.get("https://www.rejseplanen.dk/api/departureBoard?accessId=93036e26-5ec5-4fcb-ba40-395299f25046&line=True&format=json&id=" + station).text
    x = json.loads(data)
    for i in cycle_list:
        results.append(load_cycle(x, all_types.replace(i, cycle_list[i])))

    def flatten_comprehension(return_list):
        return [item for row in return_list for item in row]
    
    results = flatten_comprehension(results)

    if len(results):
        v.operators[country][operator][station]["departures"] = results
        return results




    


def kb_lookup(operator, station, country):

    print(station)
    station = station.replace(" ", "%20")
    
    #try: xml_data  = fetch_data("xmlopen.rejseplanen.dk", 80, "/bin/rest.exe/location?input=" + station)
    try: xml_data = requests.get("https://www.rejseplanen.dk/api/location.name?accessId=93036e26-5ec5-4fcb-ba40-395299f25046&input=" + station).text
    except Exception as e: print("Error. ", e)
    #print(xml_data)
    
    root = ET.fromstring(xml_data)
    
    location_data = {
        
        "locations": []
        
    }

    for location in root:
        location_type = location.tag
        location_details = {}

        # Extract attributes from 'StopLocation' and 'CoordLocation' tags
        for attribute in location.attrib:
            location_details[attribute] = location.attrib[attribute]

        location_data['locations'].append({location_type: location_details})

    json_data = json.dumps(location_data)
    data = json.loads(json_data)
    search_list = {}
    for stations in data["locations"]:
        for i in stations:
            try: 
                print(stations[i]["name"])
                print(stations[i]["extId"])
                name = stations[i]["name"]
                siteid = stations[i]["extId"]
                v.sites[country][operator][name] = siteid
                search_list[name] = siteid
            except Exception as e:
                print("Error: ", e)
    return search_list
