from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QGridLayout, QLabel, QDialog, QPushButton, QCheckBox, QSlider, QWidget, QHBoxLayout, \
    QSpinBox

from school_ringer_modules.config import config_path
from school_ringer_modules.system import run_command


class PlayMusicOnBreaksDialog(QDialog):
    def __init__(self, flags, *args, **kwargs):
        super().__init__(flags, *args, **kwargs)
        self.initUI()
        self.music_folder = run_command(f'py-ini-config get {config_path}/school-ringer.conf Main music_folder')

    def choose_music_folder(self) -> None:
        """
        Выбор папки для воспроизведения оттуда музыки на переменах
        """
        self.music_folder = run_command(f'kdialog --getexistingdirectory "{self.current_folder}" '
                                        f'--title="Выберите папку с музыкой"').strip()
        self.chosen_folder_label.setText(self.music_folder)

    def low_music_level_checkbox_toggle(self) -> None:
        """
        Обработка нажатия чекбокса, отвечающего за приглушение музыки на переменах
        """
        if self.low_music_level_checkbox.isChecked():
            self.slider.setEnabled(True)
        else:
            self.slider.setEnabled(False)
            self.slider.setValue(100)

    def volume_level_adjust(self) -> None:
        """
        Обработка движения ползунка, отвечающего за громкость музыки на переменах
        """
        self.low_music_level_checkbox.setText(f'Громкость музыки: {self.slider.value():3}%')

    def change_pause_enable(self) -> None:
        """
        Меняет доступность редактирования паузы перед музыкой на перемене
        """
        if self.pause_required_checkbox.isChecked():
            self.pause_widget.setEnabled(True)
        else:
            self.pause_widget.setDisabled(True)

    def initUI(self):
        layout = QGridLayout()
        self.setLayout(layout)
        layout.addWidget(QLabel('Выберите папку с музыкой:'), 0, 0, 1, 2)
        choose_folder_button = QPushButton('Выбрать папку')
        choose_folder_button.clicked.connect(self.choose_music_folder)
        layout.addWidget(choose_folder_button, 1, 0, 1, 2)
        folder_label = QLabel('Выбранная папка:')
        folder_label.setAlignment(Qt.AlignRight | Qt.AlignTop)
        layout.addWidget(folder_label, 2, 0)
        self.current_folder = run_command(f'py-ini-config get {config_path}/school-ringer.conf Main music_folder').strip()
        self.chosen_folder_label = QLabel(self.current_folder)
        self.chosen_folder_label.setAlignment(Qt.AlignLeft | Qt.AlignTop)
        self.chosen_folder_label.setWordWrap(True)
        layout.addWidget(self.chosen_folder_label, 2, 1)
        self.shuffle_checkbox = QCheckBox('Перемешать треки')
        layout.addWidget(self.shuffle_checkbox, 3, 0, 1, 2)
        music_shuffle = run_command(f'py-ini-config get {config_path}/school-ringer.conf Main music_shuffle').strip()
        if music_shuffle == 'True':
            self.shuffle_checkbox.setChecked(True)
        self.low_music_level_checkbox = QCheckBox('Громкость музыки: 100%')

        self.low_music_level_checkbox.toggled.connect(self.low_music_level_checkbox_toggle)
        layout.addWidget(self.low_music_level_checkbox, 4, 0)
        self.slider = QSlider(self)
        self.slider.setOrientation(Qt.Orientation.Horizontal)
        self.slider.setRange(0, 100)
        self.slider.setValue(100)
        self.slider.setTickPosition(QSlider.TicksBelow)
        self.slider.valueChanged.connect(self.volume_level_adjust)
        self.slider.setEnabled(False)
        layout.addWidget(self.slider)
        if run_command(f'py-ini-config get {config_path}/school-ringer.conf Main music_volume').strip() != '100':
            self.low_music_level_checkbox.setChecked(True)
            self.slider.setValue(
                int(run_command(f'py-ini-config get {config_path}/school-ringer.conf Main music_volume')))

        self.pause_required_checkbox = QCheckBox('Пауза перед музыкой:')
        self.pause_required_checkbox.toggled.connect(self.change_pause_enable)
        layout.addWidget(self.pause_required_checkbox, 5, 0)

        self.pause_widget = QWidget()
        pause_widget_layout = QHBoxLayout()
        self.pause_widget.setLayout(pause_widget_layout)
        self.pause_widget.setMinimumHeight(40)
        self.pause_minutes = QSpinBox()
        self.pause_seconds = QSpinBox()
        self.pause_minutes.setMaximum(9)
        self.pause_seconds.setMaximum(59)
        pause_widget_layout.addWidget(self.pause_minutes)
        pause_widget_layout.addWidget(QLabel('минут'))
        pause_widget_layout.addWidget(self.pause_seconds)
        pause_widget_layout.addWidget(QLabel('секунд'))
        pause = run_command(f'py-ini-config get {config_path}/school-ringer.conf Main music_pause').strip()
        if pause and int(pause) != 0:
            if pause >= 600:
                pause = 599
            pause_minutes = int(pause) // 60
            pause_seconds = int(pause) % 60
            self.pause_required_checkbox.setChecked(True)
            self.pause_minutes.setValue(pause_minutes)
            self.pause_seconds.setValue(pause_seconds)
        else:
            self.pause_minutes.setValue(0)
            self.pause_seconds.setValue(0)
            self.pause_required_checkbox.setChecked(False)
        self.change_pause_enable()
        layout.addWidget(self.pause_widget, 5, 1)

        self.ok_button = QPushButton('Ok')
        self.cancel_button = QPushButton('Cancel')
        self.ok_button.clicked.connect(self.accept)
        self.cancel_button.clicked.connect(self.reject)
        layout.addWidget(self.ok_button, 6, 0)
        layout.addWidget(self.cancel_button, 6, 1)
        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 1)

        self.setWindowTitle('Играть музыку на переменах')
        self.setMinimumWidth(400)
