#!/usr/bin/python3

import logging
import time
import schedule

from school_ringer_modules.daemon_scheduler import update_all_calls, schedule_all_calls, get_time_of_next_call
from school_ringer_modules.groups_dataclasses import AllGroupsOfCalls
from school_ringer_modules.schedules_dataclasses import AllSchedules
from school_ringer_modules.time_functions import time_string_to_minute

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)
logging.basicConfig(
    format=u'%(asctime)s %(filename)s [LINE:%(lineno)d] [%(funcName)s()] #%(levelname)-15s %(message)s',
    level=logging.INFO,
)

schedules = AllSchedules()
all_groups_of_calls = AllGroupsOfCalls()
allCalls = update_all_calls()

logging.info('All calls of daemon:', allCalls)
# allTimes = list(allCalls.keys())
allTimes = [allCalls[call]["time"] for call in allCalls.keys()]
while '-' in allTimes:
    allTimes.remove('-')
allTimes.sort(key=time_string_to_minute)
logging.info('All times of daemon:' + str(allTimes))

all_jobs = schedule_all_calls(allCalls)

# logging.info('All jobs of daemon:', str(all_jobs))

next_call = get_time_of_next_call(all_jobs)
if next_call is not None:
    logging.info(f'First task of daemon: {next_call}, {all_jobs[0]}')

while True:
    sleeping_time = schedule.idle_seconds()
    if sleeping_time is not None:
        next_call = schedule.next_run()
        logging.info(f'До следующего звонка осталось {sleeping_time} секунд')
        logging.info(f'Следующий звонок: {next_call}')
        if sleeping_time > 0:
            time.sleep(sleeping_time)
            schedule.run_pending()
    else:
        logging.info('Следующий звонок: -')
        time.sleep(5)
