import requests
import json
from pathlib import Path
from datetime import datetime, timezone

from aiohttp import payload_type
from proto import Field

USERNAME = "hubobel"
URL = "https://www.simbrief.com/api/xml.fetcher.php"
params = {
    "username": USERNAME,
    "json": 1,       # JSON statt XML
}
Pfad = 'Universal_txts/Windows'

ordnerneu = Path(Pfad + '/neu/')
ordnerneu.mkdir(exist_ok=True)

def minuten_zu_zeit(minuten) -> str:
    minuten = int(minuten)
    stunden = minuten // 60        # volle Stunden
    rest_min = minuten % 60        # verbleibende Minuten
    return f"{stunden}:{rest_min:02d}"  # zweistellige Minutenanzeige
def aircr_name(aircraft_icao):
    with open("aircraft_full.json", "r", encoding="utf-8") as f:
        aircraft_data = json.load(f)
    if aircraft_icao in aircraft_data:
        antwort = (aircraft_data[aircraft_icao]["name"])
    else:
        print("Code nicht vorhanden")
        antwort = "unbekanntes Luftfahrzeug"
    return (antwort)
def start_name(ori_icao):

    with open("airports_full.json", "r", encoding="utf-8") as f:
        ori_data = json.load(f)
    if ori_icao in ori_data:
        antwort = (ori_data[ori_icao]["name"])
    else:
        print("Code nicht vorhanden")
        antwort = "unbekannter Startflughafen"
    return (antwort)
def airlinename(name):
    with open("airlines_full.json", "r", encoding="utf-8") as f:
        airline_data = json.load(f)
    if name in airline_data:
        antwort = (airline_data[name]["name"])
    else:
        print("Code nicht vorhanden")
        antwort = "unbekanntes Luftfahrzeug"
    return (antwort)
def replacedynamic(message):
    message = message.replace('{AIRCRAFT_NAME}', aircraft_name)
    message = message.replace('{DESTINATION_NAME}', dest_name)
    message = message.replace('{AIRLINE_NAME}', airline)
    message = message.replace('{DESTINATION_CITY}', dest_name)
    message = message.replace('{ORIGIN_CITY}', origin_name)
    message = message.replace('{xml_number<general><initial_altitude>}', flightlevel)
    return (message)
def unix_to_datetime(timestamp: int) -> str:
    return datetime.fromtimestamp(timestamp, tz=timezone.utc).strftime("%d.%m.%Y %H:%M:%S")


resp = requests.get(URL, params=params, timeout=15)
resp.raise_for_status()
data = resp.json()  # dict
print(data.keys())
print(data['weights'])

general         = data.get("general", {})
origin          = data.get("origin", {})
origin_name     = start_name(origin["icao_code"])
origin_icao     = origin["icao_code"]
dest            = data.get("destination", {})
dest_name       = start_name(dest["icao_code"])
dest_icao       = dest["icao_code"]
aircraft        = data.get("aircraft", {})
time            = data.get("times", {})
block           = minuten_zu_zeit(int(time.get("sched_block"))/60)
start_time      = unix_to_datetime(int(time.get("sched_out")))
land_time       = unix_to_datetime(int(time.get("sched_in")))
aircraft_icao   = aircraft["icaocode"]
aircraft_name   = aircr_name((aircraft_icao))
airline         = airlinename(general.get("icao_airline"))
flightnumber    = general.get("flight_number")
flightlevel     = data['general']['initial_altitude']
fl              = 'FL'+str(int(flightlevel)//100)
distance        = data['general']['route_distance']
fuel            = data['fuel']['plan_ramp']
metar_origin    = data['weather']['orig_metar']
metar_dest      = data['weather']['dest_metar']
pax             = data['weights']['pax_count']
payload         = data['weights']['payload']
tow             = data['weights']['est_tow']
zfw             = data['weights']['est_zfw']

print('')
print("Airline:", general.get("icao_airline"))
print("Airlinename:", airline)
print("Flugnummer:", general.get("flight_number"))
print("Abflug ICAO:", origin.get("icao_code"))
print("von:", origin_name)
print("Ziel ICAO:", dest.get("icao_code"))
print("nach:", dest_name)
print("Geplante Blockzeit:", block)
print("geplanter Start:", start_time,"UTC")
print("geplante Landung:", land_time, "UTC")
print("Fluggerät:", aircraft_icao, aircraft_name)
print("Cruiselevel:", fl)
print("Entfernung:", distance, 'nm')
print("Fuel:", fuel, 'kg')
print("Passagiere:", pax)
print("ZFW:", zfw, 'kg')
print("TOW:", tow, 'kg')
print("Wetter:", origin.get("icao_code"), metar_origin)
print("Wetter:", dest["icao_code"], metar_dest)



for datei in Path(Pfad).glob("*.txt"):
    with open(datei, "r", encoding="utf-8") as f:
        inhalt = f.read()
        inhalt_neu = replacedynamic(inhalt)
        dateineu = str(ordnerneu) + '/' + (f"{datei.name}")
        with open(dateineu,'w', encoding="utf-8") as e:
            e.write(inhalt_neu)

