import requests
import xmltodict
import json
import os
import time

def update_station_data(jsonpath, max_age=86400):
    if not update_file(jsonpath, max_age=max_age):
        print(f"file {jsonpath} was modified less than {max_age}s ago, skipping")
        return

    url = "https://iris.noncd.db.de/iris-tts/timetable/station/*"
    x = requests.get(url)
    if x.status_code != 200:
        raise ConnectionError(f"status code {x.status_code}")

    xmlstr = x.text

    stations_list = xmltodict.parse(xmlstr, )['stations']['station']

    stations_dict = {}

    for station in stations_list:
        name = station.pop("@name")
    
        local_station = {k.strip('@'): v for k,v in station.items()}

        stations_dict[name] = local_station

    with open(jsonpath, 'w') as f:
        f.write(json.dumps(stations_dict, indent=4, ensure_ascii=False))

def update_file(fpath, max_age=86400):
    if os.path.exists(fpath):
        mtime = os.path.getmtime(fpath)
        ctime = time.time()
        if ctime - mtime < max_age:
            return False
    return True

def main():
    update_station_data("./stations/stations2.json")

if __name__ == "__main__":
    main()
