import requests
import json
from boltons import timeutils
from boltons import strutils
import datetime

with open("zha_cities.json", "r") as json_file:
    json_reader = json.load(json_file)

for data in json_reader:
    source = requests.get(f"http://api.open-notify.org/iss-pass.json?lat={data['coord']['lat']}&lon={data['coord']['lon']}").json()
    passes = source['request']['passes']
    epoch_dt = datetime.datetime.utcfromtimestamp(source['request']['datetime'])
    iso_str = epoch_dt.isoformat()
    date_strp = datetime.datetime.strptime(iso_str, '%Y-%m-%dT%H:%M:%S')
    date_str_f = date_strp.strftime("%A, %b %d, %Y - %H:%M:%S %p")
    print(f"{passes} upcoming ISS passes for {data['city']}, {data['country']}:")
    print(f"Current Coordinated Universal Time (UTC): {date_str_f}")
    for num, risetime in zip(range(1, 6), source['response']):
        rise_date = datetime.datetime.fromtimestamp(risetime['risetime'])
        duration = datetime.datetime.fromtimestamp(risetime['duration'])

        print(strutils.ordinalize(num))
        print(f"- {timeutils.relative_time(rise_date, ndigits=1)}")
        print(datetime.datetime.strftime(rise_date, "- %A, %b %d, %Y - %H:%M:%S %p"))
        print(f"- Duration: {duration.minute} minutes {duration.second} seconds")
