import v
from v import *
import random, string
from fetch import fetch_data

def vt_get_new_token():
    url = "https://ext-api.vasttrafik.se/token"
    msg = """grant_type=client_credentials"""

    data = requests.post(url, data=msg, headers={'Content-Type': 'application/x-www-form-urlencoded', "Authorization":"Basic TVNvTTBacjJvcjIyNU5sMk5Gdzd4TDN6TVRvYTppSFlJOF80ZlhveWQ3VkhRZjJMMjhRY0dYOU1h"}).text
    data = json.loads(data)
    print(data["access_token"])
    with open("vt_token.txt", "w") as p:
        p.write(data["access_token"])

def vt_load_token():
    with open("vt_token.txt", "r") as p:
        return p.read()


def sl_load_departures(siteid, operator="sl", country="se"):
    def converttime(ts): return time.mktime(time.struct_time((int(ts[:4]),int(ts[5:7]),int(ts[8:10]),int(ts[11:13]),int(ts[14:16]),int(ts[17:19]),0,-1,-1)))
    random_string = ''.join(random.choices(string.ascii_letters, k=10)) + "=true"
    fetched_data = json.loads(fetch_data(host=v.servers["departures"][0], args=v.servers["departures"][1] + str(siteid) + "/departures?" + random_string))
    #fetched_data = json.loads(requests.get("https://transport.integration.sl.se/v1/sites/"+siteid+"/departures").text)
    temp_departures = {}
    temp_departures[siteid] = {"departures":[], "timestamp":(time.mktime(time.localtime()))}
    #try:
    #    if siteid in v.siteids.siteId:
    #        pass
    #except: v.siteids.siteId[siteid] = fetched_data["departures"][0]["stop_area"]["name"]
    #####################
    for i in fetched_data["departures"]:
        if i["deviations"]:
            if "list" in str(type(i["deviations"])): i["deviations"] = i["deviations"][0]
            n = "".join(i["deviations"]["message"]).lower()
            if "inställd" in n and not "inställda" in n: continue
        if converttime(i["expected"]) > time.mktime(time.localtime()):
            i["line"]["id"] = i["line"]["designation"]
            temp_departures[siteid]["departures"].append({"destination":i["destination"].replace("NÄRTRAFIKEN","Närtrf."),
                    "direction_code":i["direction_code"],
                    "expected":i["expected"],
                    "line":i["line"],
                    "deviations":i["deviations"]})
    if len(temp_departures[siteid]["departures"]) > 0: #v.departures[siteid] = temp_departures[siteid]
        v.operators[country][operator][siteid] = temp_departures[siteid]
    return temp_departures[siteid]

def sl_get_deviations(country, operator, station):
    if time.mktime(time.localtime()) < v.operators[country][operator][station]["timestamp"] + v.deviations_update_delay: return
    v.operators[country][operator][station] = {"timestamp":time.mktime(time.localtime())}
    print("OK")
    data = json.loads(fetch_data(host=v.servers["deviations"][0], args=v.servers["deviations"][1], port=80))
    deviations_list = []
    test = []
    for i in data:
        importance = i["priority"]["importance_level"] * i["priority"]["influence_level"] * i["priority"]["urgency_level"]
        try:
            for ii in i["scope"]["stop_areas"]:
                test.append(ii["name"])
                data = test
        except: pass
        if importance > 1:
            try:
                _deviation_message = i["scope"]["lines"][0]["name"] + ": " + i["message_variants"][0]["header"]
                if "Närtrafiken" in _deviation_message: continue
                if not _deviation_message in deviations_list: 
                    deviations_list.append(_deviation_message)
                    #v.deviations_dict.append(i)
                v.deviations_list = deviations_list
            except: pass

    return deviations_list
    #return v.operators[country][operator][station]

def sort_dict_by_keys(dictionary):
    sorted_keys = sorted(dictionary.keys())
    sorted_dict = dict(zip(sorted_keys, [dictionary[key] for key in sorted_keys]))
    return sorted_dict

def sj_load_deviations(station, operator, country="se"):
    msg = """<REQUEST>
    <LOGIN authenticationkey='63ea83cd2cce48c79eaebf475818b7d0'/>
    <QUERY objecttype='TrainMessage' schemaversion='1.3'>
    <FILTER>
    <IN name='AffectedLocation' value='"""+station+"""'/>
    </FILTER>
    <EXCLUDE>Deleted</EXCLUDE>
    </QUERY>
    </REQUEST>"""
    response = requests.post("https://api.trafikinfo.trafikverket.se/v2/data.json", data=msg, headers={'Content-Type': 'text/xml'})
    deviations = json.loads(response.text)
    results = []
    for x, deviation in enumerate(deviations["RESPONSE"]["RESULT"]):
        for i in deviation["TrainMessage"]:
            #print(x,"--------", deviation)
            if station in (i["AffectedLocation"]):
                #print("Found ", station, " in ", i["AffectedLocation"], i["ExternalDescription"])
                results.append(i["ExternalDescription"].replace("\n"," "))
            #print("-----------",i)
    v.operators[country][operator][station]["deviations"] = results
    return results

def sj_load_departures(station, operator, country="se"):
    print("Stations: ", station)
    #if station == "M": station = "Mc"
    #if station == "Vb": station = "Vbc"

    try: station = x.encode('utf-8', 'replace').decode('utf-8')
    except: pass
    country = "se"
    now = datetime.datetime.now()
    now_str = now.strftime("%H:%M:%S")  # Convert to string in HH:MM:SS format
    now_str = "$dateadd(00:00:00)"
    hours = datetime.timedelta(hours=7)
    try: 
        if len(v.operators[country][operator][station]["departures"]) < 4: hours = datetime.timedelta(hours=7)
    except:  hours = datetime.timedelta(hours=4)
    print(" --------------------------------------- ",hours)
    later = now + hours  # Add the timedelta object to the datetime object
    later_str = later.strftime("%H:%M:%S")  # Convert to string in HH:MM:SS format
    later_str = "$dateadd(03:00:00)"
    msg = """<REQUEST>
                <LOGIN authenticationkey='63ea83cd2cce48c79eaebf475818b7d0' />
                <QUERY objecttype='TrainAnnouncement' orderby='AdvertisedTimeAtLocation' schemaversion='1'>
                    <FILTER>
                    <AND>
                        <OR>
                            <AND>
                                <GT name='AdvertisedTimeAtLocation' value='""" + now_str + """' />
                                <LT name='AdvertisedTimeAtLocation' value='"""+ later_str +"""' />
                            </AND>
                            <GT name='EstimatedTimeAtLocation' value='""" + now_str + """' />
                        </OR>
                        <EQ name='LocationSignature' value='""" + station + """' />
                        <EQ name='ActivityType' value='Avgang' />
                    </AND>
                    </FILTER>
                    <INCLUDE>InformationOwner</INCLUDE>
                    <INCLUDE>Canceled</INCLUDE>
                    <INCLUDE>AdvertisedTimeAtLocation</INCLUDE>
                    <INCLUDE>TrackAtLocation</INCLUDE>
                    <INCLUDE>FromLocation</INCLUDE>
                    <INCLUDE>EstimatedTimeAtLocation</INCLUDE>
                    <INCLUDE>ToLocation</INCLUDE>
                </QUERY>
                </REQUEST>"""
    root = ET.fromstring(msg)
    msg = ET.tostring(root).decode('utf-8')
    response = requests.post("https://api.trafikinfo.trafikverket.se/v2/data.json",timeout=4, data=msg, headers={'Content-Type': 'text/xml'})
    departures = json.loads(response.text)
    print(str(departures)[:350])
    results = []
    #print("DEPARTURES:" , departures)
    for i in departures:
        for ii in departures[i]["RESULT"][0]["TrainAnnouncement"]:
            try: line = ii["InformationOwner"][:3]
            except: line = "0"
            destination = ii["ToLocation"]
            if len(destination) > 1: destination = destination[-1]
            else: destination = ii["ToLocation"][0]
            try: destination = list(v.sj_stations.keys())[list(v.sj_stations.values()).index(destination)]
            except: 
                try: 
                    destination = destination.replace("Mc","Malmö C")
                    destination = destination.replace("Vbc","Varberg C")
                except: pass
                
            #_time = ii["AdvertisedTimeAtLocation"][:19]
            try: 
                _time = ii["EstimatedTimeAtLocation"][:19]
                print(" ================== DELAYED =================")
            except: 
                _time = ii["AdvertisedTimeAtLocation"][:19]
                print("SCHEDULED")



            __line = ii["InformationOwner"][:3]
            _canceled = ii["Canceled"]
            #print(_canceled)
            __destination_and_line = destination + " " + __line
            departures_dict = {"destination":destination, 
                               "direction_code":"0",
                               "expected": _time,
                               "line": {"id": line, "transport_mode":"TRAIN"},
                               "deviations":[]}
            if not _canceled: results.append(departures_dict)
    
    #if len(results): v.operators[country][operator][station] = {"departures" : results, "timestamp" : time.mktime(time.localtime())}
    print("RESULTS" , len(results))
    if len(results):
        #if station == "Mc": station = "M"
        #if station == "Vbc": station = "Vb"
        v.operators[country][operator][station] = {"departures" : results, "timestamp" : time.mktime(time.localtime())}
        return results
    #try: sj_load_deviations(station=station, operator=operator, country=country)
    #except: pass

def sj_load_stations():
    msg = """<REQUEST>
    <LOGIN authenticationkey='63ea83cd2cce48c79eaebf475818b7d0'/>
    <QUERY objecttype='TrainStation' schemaversion='1'>
    <FILTER/>
    <INCLUDE>Prognosticated</INCLUDE>
    <INCLUDE>AdvertisedLocationName</INCLUDE>
    <INCLUDE>LocationSignature</INCLUDE>
    </QUERY>
    </REQUEST>"""
    response = requests.post("https://api.trafikinfo.trafikverket.se/v2/data.json", data=msg, headers={'Content-Type': 'text/xml'})
    stations = json.loads(response.text)
    stations_dict = {}
    for i in stations:
        for ii in stations[i]["RESULT"][0]["TrainStation"]:
            name = ii["AdvertisedLocationName"]
            short_name = ii["LocationSignature"]
            #stations_dict[short_name] = name
            stations_dict[name] = short_name
    with open("sj_stations.txt", "w") as f:
        f.write(json.dumps(stations_dict))
    return stations_dict

def sj_lookup(operator, station, country="se"):
    
        #data = fetch_data("journeyplanner.integration.sl.se", 80, "/v1/typeahead.json?key=2ab4d947683c4a60b1a90fd2324eb4c5&searchstring=" + station)
        #data = sj_load_stations()
        data = v.sj_stations
        search_list = {}
        for stations in data:
            #print(stations, print(data[stations]))
            if station[:5].lower() in stations.lower():
                name = stations
                shortname = data[stations]
                #print(shortname)
                v.sites[country][operator][name] = shortname
                search_list[name] = shortname
        return search_list

def sl_lookup(operator, station, country="se"):
    print(station)
    station = station.replace(" ", "%20")
    station = station.replace("ö", "o").replace("ä","a").replace("å", "a")
    station = station.replace("Ö", "O").replace("Ä","a").replace("Å", "a")
    url1 = "journeyplanner.integration.sl.se"
    url2 = "/v2/stop-finder?name_sf=" + station + "&any_obj_filter_sf=2&type_sf=any"
    try: data  = fetch_data(url1, 80, url2)
    except Exception as e: print("Error. ", e)
    print(data)
    try: 
        data = json.loads(data)                  
        #print(data)
        search_list = {}
        for stations in data["locations"]:
            name = stations["disassembledName"] + ", " + stations["parent"]["name"]
            siteid = stations["id"][-4:]#.replace("8125","8000")
            #siteid = stations["properties"]["stopId"][-4:].replace("8125","8000")
            v.sites[country][operator][name] = siteid
            search_list[name] = siteid
        #print("SL", search_list)
        #search_list = search_list.replace("8125","8000")
        return search_list
    except Exception as e:
        print("Error: ", e)


def _sl_lookup(operator, station, country="se"):
    print(station)
    station = station.replace(" ", "%20")
    try: data  = fetch_data("journeyplanner.integration.sl.se", 80, "/v1/typeahead.json?key=2ab4d947683c4a60b1a90fd2324eb4c5&searchstring=" + station)
    except Exception as e: print("Error. ", e)
    print(data)
    try: 
        data = json.loads(data)                  
        #print(data)
        search_list = {}
        for stations in data["ResponseData"]:
            name = stations["Name"]
            siteid = stations["SiteId"][-4:]
            v.sites[country][operator][name] = siteid
            search_list[name] = siteid
        #print("SL", search_list)
        return search_list
    except Exception as e:
        print("Error: ", e)





def vt_load_departures(gid, operator, country="se"):
    country = "se"
    #gid = "9021014001760000"
    #print(gid)
    url = """https://ext-api.vasttrafik.se/pr/v4/stop-areas/""" + gid + """/departures?timeSpanInMinutes=60&limit=110&maxDeparturesPerLineAndDirection=5"""
    data = requests.get(url, headers={'accept': 'text/plain', "Authorization":"Bearer " + v.token}).text
    data = json.loads(data)
    if "fault" in data:
        if "Invalid" in data["fault"]["description"]:
            vt_get_new_token()
            v.token = vt_load_token()
            print("-----------------Invalid token------------")
    #print(data)
    data = data["results"]
    #print(data)
    results = []
    counter = 0
    for departures in data:
        try:
            """destination = {"destination":departures["serviceJourney"]["directionDetails"]["shortDirection"]}
            line = (departures["serviceJourney"]["line"]["shortName"])
            time = (departures["plannedTime"][:19])
            new_departure = [line, destination, time]
            #print(departures["estimatedTime"])
            #results.append(new_departure)"""
            try: 
                if departures["isCancelled"]: continue
            except: pass
            try: 
                available_time = departures["estimatedTime"][:19]
                print("ESTIMATED")
            except: 
                available_time = departures["plannedTime"][:19]
                print("PLANNED")
        
            new_record = {"destination" : departures["serviceJourney"]["directionDetails"]["shortDirection"],
                        "direction_code" : "0",
                        "expected" : available_time,
                        "line" : {"id": departures["serviceJourney"]["line"]["shortName"].replace("-","."), "transport_mode":departures["serviceJourney"]["line"]["transportMode"].replace("ferry","ship").upper()},
                        "deviations": []}
            
            # 1
            #if not new_record in results:    
            #    results.append(new_record)
            # 2
            results.append(new_record)
      
      
            #v.operators[operator][gid]["departures"].append(new_record)
        except Exception as e: 
            #print(v.operators[country][operator])
            print("Error: ", e)
            return
    if len(results):
        v.operators[country][operator][gid]["departures"] = results
        print("Success")
        return results

def vt_lookup(_string):
    url = """https://ext-api.vasttrafik.se/pr/v4/locations/by-text?q=""" + _string + """&limit=30&offset=0"""
    data = requests.get(url, headers={'accept': 'text/plain', "Authorization":"Bearer " + v.token}).text
    data = json.loads(data)
    if "fault" in data:
        print("FAULT")
        if "Invalid" in data["fault"]["description"]:
            vt_get_new_token()
            v.token = vt_load_token()
            print("-----------------Invalid token------------")
    data = data["results"]
    results = {}
    search_list = {}
    for stops in data:
        try:
            if _string[:5].lower() in stops["name"].lower():
                    name = stops["name"]
                    gid = stops["gid"]
                    search_list[name] = gid
        except Exception as e: print("Error: ", e)
    return search_list

def ferries_load_stations():
    msg = """<REQUEST>
    <LOGIN authenticationkey='63ea83cd2cce48c79eaebf475818b7d0'/>
    <QUERY objecttype='FerryRoute' schemaversion='1.2'>
    <FILTER/>
    <INCLUDE>Harbor</INCLUDE>
    
    
    </QUERY>
    </REQUEST>"""
    response = requests.post("https://api.trafikinfo.trafikverket.se/v2/data.json", data=msg, headers={'Content-Type': 'text/xml'})
    stations = json.loads(response.text)
    #print(stations)
    stationlist = stations["RESPONSE"]["RESULT"][0]
    stationlist = stationlist["FerryRoute"]
    stations_dict = {}
    for i in stationlist:
        id0 = str(i["Harbor"][0]["Id"])
        name0 = i["Harbor"][0]["Name"]
        id1 = str(i["Harbor"][1]["Id"])
        name1 = i["Harbor"][1]["Name"]
        
        stations_dict[name0] = id0
        stations_dict[name1] = id1
        #stations_dict[id0] = name0
        #stations_dict[id1] = name1
        
    #print(stations_dict)
    #v.ferries_stations = stations_dict
    with open("ferries_stations.txt", "w") as f:
        f.write(json.dumps(stations_dict))
    return stations_dict

def ferries_lookup(operator, station, country="se"):
        print("Station: ", station)
        
        #data = v.ferries_stations
        data  = ferries_load_stations()
        search_list = {}
        for stations in data:
            #print(stations, print(data[stations]))
            if station[:5].lower() in stations.lower():
                
                name = stations
                shortname = data[stations]
                #print(shortname)
                #v.sites[country][operator][name] = shortname
                search_list[name] = shortname
        print(search_list)
        return search_list

def ferries_load_departures(station, operator="fe", country="se"):
    
    
    now = datetime.datetime.now()
    now_str = now.strftime("%H:%M:%S")  # Convert to string in HH:MM:SS format
    now_str = "$dateadd(00:00:00)"
    hours = datetime.timedelta(hours=7)
    hours = datetime.timedelta(hours=4)
    print(" --------------------------------------- ",hours)
    later = now + hours  # Add the timedelta object to the datetime object
    later_str = later.strftime("%H:%M:%S")  # Convert to string in HH:MM:SS format
    later_str = "$dateadd(03:00:00)"
    msg = """<REQUEST>
                <LOGIN authenticationkey='63ea83cd2cce48c79eaebf475818b7d0' />
                <QUERY objecttype='FerryAnnouncement' schemaversion='1.2'>
                <FILTER>
                    <AND>
                        <OR>
                            <AND>
                                <GT name='DepartureTime' value='""" + now_str + """' />
                                <LT name='DepartureTime' value='"""+ later_str +"""' />
                            </AND>
                        </OR>
                        
                    </AND>
                    </FILTER>
    
               <INCLUDE>Deleted</INCLUDE>
               <INCLUDE>DepartureTime</INCLUDE>
                <INCLUDE>FromHarbor</INCLUDE>
                <INCLUDE>ToHarbor</INCLUDE>
                </QUERY>
                </REQUEST>"""
    root = ET.fromstring(msg)
    msg = ET.tostring(root).decode('utf-8')
    response = requests.post("https://api.trafikinfo.trafikverket.se/v2/data.json",timeout=4, data=msg, headers={'Content-Type': 'text/xml'})
    departures = json.loads(response.text)
    departures = departures["RESPONSE"]["RESULT"][0]["FerryAnnouncement"]
    results = []
    #print("DEPARTURES:" , departures)
    for i in departures:
        if str(i["FromHarbor"]["Id"]) == station: 
            if i["Deleted"]: continue
            _time = i["DepartureTime"][:19]
            destination = i["ToHarbor"]["Name"]
            
            
            
            departures_dict = {"destination":destination, 
                               "direction_code":"0",
                               "expected": _time,
                               "line": {"id": "0", "transport_mode":"SHIP"},
                               "deviations":[]}
            results.append(departures_dict)
        
        
    #if len(results): v.operators[country][operator][station] = {"departures" : results, "timestamp" : time.mktime(time.localtime())}"""
    print("RESULTS" , results, len(results))
    if len(results):
        v.operators[country][operator][station] = {"departures" : results, "timestamp" : time.mktime(time.localtime())}
        return results
    
def resrobot_lookup(operator, station, country="se"):
    
    key = "f915361c-f370-4ee6-a371-2110e6a79b92"
    url = "https://api.resrobot.se/v2.1/location.name?input=" + station + "&format=json&accessId=" + key
    data = requests.get(url).text
    try:
        data = json.loads(data)
        data = data["stopLocationOrCoordLocation"]
    except Exception as e:
        print(e)
        return "0"
    print(data)
    search_list = {}
    for stations in data:
        try:
            name = stations["StopLocation"]["name"]
            siteid = stations["StopLocation"]["extId"]
            search_list[name] = siteid
        except Exception as e:
            print(e)
    return search_list
    

def resrobot_load_departures(station, operator):
    
    country="se"
    key = "f915361c-f370-4ee6-a371-2110e6a79b92"
    url = "https://api.resrobot.se/v2.1/departureBoard?id="+station+"&format=json&accessId=" + key
    data = requests.get(url).text
    try:
        data = json.loads(data)
    except Exception as e:
        print(e)
        return "0"
    print(data)
    departures = data
    results = []
    print(departures)
    for i in departures["Departure"]:
        #print(i)
        try:
            id = str(i["ProductAtStop"]["displayNumber"])
            _time = str(i["time"])
            direction = i["direction"].split("(")[0]
            _date = str(i["date"])
            _time = _date + "T" + _time
            print(id, _time, direction)

        except Exception as e:
            print(e)
        

        #id = i["operatorInfo"]["id"]
        #print(id)
        #_time = i["DepartureTime"][:19]
        #destination = i["ToHarbor"]["Name"]
        
        
        
        departures_dict = {"destination":direction, 
                            "direction_code":"0",
                            "expected": _time,
                            "line": {"id": id, "transport_mode":"BUS"},
                            "deviations":[]}
        results.append(departures_dict)
        
        
    #if len(results): v.operators[country][operator][station] = {"departures" : results, "timestamp" : time.mktime(time.localtime())}"""
    print("RESULTS" , results, len(results))
    if len(results):
        v.operators[country][operator][station] = {"departures" : results, "timestamp" : time.mktime(time.localtime())}

        return results
#resrobot_lookup(station="lule", operator="norrland")
#resrobot_load_departures(station="740000144", operator="norrland")
