import logging
from datetime import datetime, timedelta
from subprocess import run

import dbus


def run_command(command: str) -> str:
    """
    Выполнение команды и сохранение вывода в лог
    :param command: команда shell
    :return: результат работы команды
    """
    logging.info(f'Command called: {command}')
    ret = run(command, capture_output=True, shell=True)
    logging.info(f"[{command}]>{ret.stdout.decode()}")
    print(f"[{command}]>{ret.stdout.decode()}")
    return ret.stdout.decode()


def get_current_user_on_x():
    try:
        loginctl_lines = run_command('loginctl').strip().split('\n')
        tty_session_ids = dict()
        for line in loginctl_lines[1:]:
            if len(line.strip().split()) > 0 and 'tty' in line.strip().split()[-1] and \
                    int(line.strip().split()[1]) >= 500:
                tty_session_ids[line.strip().split()[0]] = line.strip().split()[2]
        for session_id in tty_session_ids.keys():
            session_status = run_command(f'loginctl show-session --property Active --value {session_id}').strip()
            if session_status == 'yes':
                print(tty_session_ids[session_id])
                return tty_session_ids[session_id]
        return run_command('who').split()[0]
    except Exception as e:
        logging.info('Не удалось получить текущего пользователя на X. Возвращаем None...')
        return None


def authority_check(action_id="ru.mos.os.school-ringer"):
    bus = dbus.SystemBus()
    proxy = bus.get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority')
    authority = dbus.Interface(proxy, 'org.freedesktop.PolicyKit1.Authority')

    system_bus_name = bus.get_unique_name()

    subject = ('system-bus-name', {'name': system_bus_name})
    details = {}
    flags = 1  # AllowUserInteraction flag
    cancellation_id = ''  # No cancellation id

    result = authority.CheckAuthorization(subject, action_id, details, flags, cancellation_id)
    if result[0] == 0:
        print('Авторизация не пройдена!')
    return result[0]


#
# def get_music_config():
#     res = {
#         'is_breaks_music_on': False,
#         'music_folder': '/home',
#         'music_shuffle': False
#     }
#     with open(f'{config_path}/school-ringer.conf', 'r') as inp:
#         lines = inp.readlines()
#         for line in lines:
#             if line.strip().startswith('is_breaks_music_on'):
#                 res['is_breaks_music_on'] = line.strip().split('=')[-1].strip()
#             if line.strip().startswith('music_folder'):
#                 res['music_folder'] = line.strip().split('=')[-1].strip()
#             if line.strip().startswith('music_shuffle'):
#                 res['music_shuffle'] = line.strip().split('=')[-1].strip()
#     return res

def reset_log_to_last_week(log_file):
    with open(log_file) as inp:
        lines = inp.readlines()

    week_ago = datetime.today() - timedelta(7)
    first_line = -1
    for i in range(len(lines)):
        lines[i] = lines[i].strip()

    for i in range(len(lines)):
        try:
            date = datetime.strptime(lines[i].split()[0], "%Y-%m-%d")
        except Exception:
            continue

        if date.date() >= week_ago.date():
            first_line = i
            break
    if first_line == -1:
        first_line = len(lines)

    lines = lines[first_line:]
    while '' in lines:
        lines.remove('')
    while '\n' in lines:
        lines.remove('\n')
    with open(log_file, 'w') as out:
        print(*lines, file=out, sep='\n')
