import argparse
import keyboard
import datetime
import time
import httpx

from threading import Event, Thread


def update(url: str):
    r = httpx.get(url)


def update_thread(stop: Event, url: str):
    t = datetime.time(hour=2)
    print('Starting update thread.')
    while True:
        if stop.isSet():
            break

        if datetime.time() == t:
            print('Updating.')
            update(url)

        print('Sleep')
        time.sleep(60 * 60 * 5)
    print('Stop update thread.')


def main_thread(stop: Event):
    print('Starting main thread.')
    while True:
        if stop.isSet():
            break
        try:
            if keyboard.is_pressed('q'):
                print('Stop')
                stop.set()
                break
        except KeyboardInterrupt:
            print('Stop2')
            stop.set()
            break
    print('Stop main thread.')


def main(args):
    print('Main')
    stop_signal = Event()
    threads = [
        Thread(target=update_thread, args=(stop_signal, args.url, )),
        Thread(target=main_thread, args=(stop_signal,))
    ]
    [t.start() for t in threads]
    while True:
        try:
            if True not in [t.is_alive() for t in threads]:
                break
        except KeyboardInterrupt:
            print('Stop Main')
            stop_signal.set()
            break
    [t.join() for t in threads]


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--url', help='API Url', default='http://localhost:8081/update')
    _args = parser.parse_args()
    main(_args)
