#!/usr/bin/python3

import logging
import os
import sys

from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox

from school_ringer_modules.config import config_path, icon_file
from school_ringer_modules.system import run_command, authority_check, get_current_user_on_x, reset_log_to_last_week

# Директория приложения
basedir = os.path.dirname(__file__)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon(os.path.join(basedir, icon_file)))
    try:
        from school_ringer_modules.settings import CallsSettings

        # Создание папки с конфигом, если её нет
        if not run_command(f'file {config_path}').strip().endswith(': directory'):
            run_command(f'pkexec mkdir -p {config_path}')

        current_user_on_x = get_current_user_on_x()
        if current_user_on_x:
            filename = f"/home/{current_user_on_x}/.config/school-ringer-log.txt"
        else:
            filename = f"/tmp/school-ringer-log.txt"
        # run_command(f'touch {filename}')

        # Настройка логирования
        for handler in logging.root.handlers[:]:
            logging.root.removeHandler(handler)
        logging.basicConfig(
            # filename=f"{filename}",
            filename=filename,
            format=u'%(asctime)s %(filename)s [LINE:%(lineno)d] [%(funcName)s()] #%(levelname)-15s %(message)s',
            level=logging.INFO,
            force=True
        )
        reset_log_to_last_week(filename)
        if authority_check("ru.mos.os.school-ringer"):
            ex = CallsSettings(app)
            app.exec_()
            logging.info(f'Приложение завершило работу')
    except Exception as e:
        error_box = QMessageBox.critical(QWidget(), "Ошибка", f'({e})')
        logging.info(f'Root exception: ({e})')
    try:
        sys.exit(app)
    except Exception as e:
        print(f'Приложение не было запущено. {e}')
