def download_timetable(cache_path):
    try:
        timetable_db = shelve.open(cache_path, writeback=True)
    except OSError as e:
        fatal_error("Не удалось использовать базу: {}".format(e.strerror))
        return

    try:
        groups = sorted(get_all_groups(), key=lambda x: x[1])
        total_number = len(groups)
        log_info('{} - {}'.format(TOTAL_DECS, total_number))

        loaded_number = [x[1] for x in groups].index(max(timetable_db.keys())) + 1 if len(timetable_db) else 0
        log_info('{} - {}'.format(LOADED_DECS.rjust(len(TOTAL_DECS)), str(loaded_number).rjust(len(str(total_number)))))

        groups = groups[loaded_number:]

        for group_id, group_name in groups:
            log_info(r'{}/{}'.format(str(loaded_number + 1).rjust(len(str(total_number))), total_number))
            timetable_db[group_name] = parse_group_timetable(ET.fromstring(load_group_timetable(group_id)))
            loaded_number += 1
    except (ConnectionError, TimeoutError, urllib.error.HTTPError, urllib.error.URLError):
        fatal_error('Невозможно загрузить данные. Проверьте соединение с интернетом!')
    finally:
        timetable_db.close()
def write_result(busyness, result_file):
    days_list = ['Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота']

    try:
        log_info('Запись результата...\n')
        f = open(result_file, 'w', encoding='utf-8')

        for auditorium in sorted(busyness.keys(), key=lambda x: (x[1], x[0])):
            f.write('{}-{}:\n'.format(auditorium[0], auditorium[1]))
            for week_day in sorted(busyness[auditorium], key=lambda x: days_list.index(x)):
                f.write('\t{}:\n'.format(week_day))
                for week_number in busyness[auditorium][week_day]:
                    f.write('\t\tнеделя {}\n'.format(week_number))
                    for lesson_time in sorted(busyness[auditorium][week_day][week_number], key=lambda x: x[1]):
                        lesson_info = busyness[auditorium][week_day][week_number][lesson_time]

                        f.write('\t' * 3 + '{}\n'.format(repr_lesson_time(lesson_time)))
                        f.write('\t' * 4 + 'предмет: {}\n'.format(lesson_info['subject']))
                        f.write('\t' * 4 + 'преподаватель: {}\n\n'.format(repr_employee(lesson_info['employee'])))

                        for group in sorted(lesson_info['groups']):
                            f.write('\t' * 4 + 'группа {}\n'.format(group))
    except OSError as e:
        fatal_error("Не удалось записать результат: {}".format(e.strerror))
import sys
from helper import fatal_error, press_enter
from downloader import download_timetable
from busyness_info_builder import build_auditoriums_busyness, write_result

if __name__ == '__main__':
    if len(sys.argv) != 3:
        fatal_error("Недостаточно параметров!")

    timetable_cache_path = sys.argv[1]
    result_file_path = sys.argv[2]

    download_timetable(timetable_cache_path)
    write_result(build_auditoriums_busyness(timetable_cache_path), result_file_path)

    press_enter()