from PyQt5.QtWidgets import QWidget, QLineEdit, QSpinBox, QComboBox, \
    QPushButton, QColorDialog, QCheckBox, QDoubleSpinBox
from PyQt5.QtGui import QColor, QPalette, QIcon
from PyQt5.QtCore import pyqtSignal

from ui.ui_settings import Ui_Settings
from settings import Settings as AppSettings

import functools


class Settings(QWidget, Ui_Settings):

    signalChanged = pyqtSignal(str, object)

    def __init__(self, panel, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        Ui_Settings.setupUi(self, self)
        self.setWindowTitle('Kumite App - Configuración')
        self.setWindowIcon(QIcon(":images/logo.png"))
        self.__load()
        self.__connect()
        self.PromptShowButton.clicked.connect(panel.show_prompt)
        self.SoundFinalEdit.config('Sonido final', 'Open file (*.mp3 *.ogg *.wav)')
        self.SoundFirstEdit.config('Primer sonido', 'Open file (*.mp3 *.ogg *.wav)')
        self.SoundSecondEdit.config('Segundo sonido', 'Open file (*.mp3 *.ogg *.wav)')
        self.tabs.setCurrentIndex(0)

        map_groups = {
            'team': self.PromptTeamsSpinbox,
            'category': self.PromptCategorySpinbox,
            'modality': self.PromptModalitySpinbox,
            'tatami': self.PromptTatamiSpinbox,
            'time': self.PromptTimeSpinbox,
            'point': self.PromptPointsSpinbox,
            'penalty': self.PromptPenaltySpinbox,
            'member': self.PromptMemberSpinbox,
            'senshu': self.PromptSenshuSpinbox,
        }
        for k, w in map_groups.items():
            w.valueChanged.connect(functools.partial(self.__emit_changed, k))

    def __emit_changed(self, group, value):
        self.signalChanged.emit(group, value)

    def closeEvent(self, event):
        self.__save()

    def __connect(self):
        for s, w in AppSettings().get_widgets(self, QColor):
            w.clicked.connect(functools.partial(self.__color_change, s, w))

    def __color_change(self, setting, widget):
        color = QColorDialog.getColor()
        if color:
            self.__button_color(widget, color)

    def __button_color(self, widget, color):
        pal = widget.palette()
        pal.setColor(QPalette.Button, color)
        widget.setPalette(pal)

    def __load(self):
        for group in AppSettings().groups():
            for item in group.items():
                if not item.widget: continue
                w = getattr(self, item.widget)
                if type(w) == QLineEdit:
                    w.setText(item.get())
                elif type(w) in (QSpinBox, QDoubleSpinBox):
                    w.setValue(item.get())
                elif type(w) == QPushButton:
                    if item.type == bool:
                        w.setChecked(item.get())
                    elif item.type == QColor:
                        self.__button_color(w, item.get())
                elif type(w) == QCheckBox:
                    w.setChecked(item.get())
                elif type(w) == QComboBox:
                    w.setCurrentText(item.get())

        sounds = AppSettings().sounds
        self.SoundFinalEdit.load(sounds['time_1'].get()[1])
        self.SoundFirstSpinbox.setValue(int(sounds['time_2'].get()[0]))
        self.SoundFirstEdit.load(sounds['time_2'].get()[1])
        self.SoundSecondSpinbox.setValue(int(sounds['time_3'].get()[0]))
        self.SoundSecondEdit.load(sounds['time_3'].get()[1])

    def __save(self):
        for group in AppSettings().groups():
            for item in group.items():
                if not item.widget: continue
                w = getattr(self, item.widget)
                if type(w) == QLineEdit:
                    item.set(w.text())
                elif type(w) == QSpinBox:
                    item.set(w.value())
                elif type(w) == QPushButton:
                    if item.type == bool:
                        item.set(w.isChecked())
                    elif item.type == QColor:
                        c = w.palette().color(QPalette.Active, QPalette.Button)
                        item.set(c)
                elif type(w) == QComboBox:
                    item.set(w.currentText())
                elif type(w) == QCheckBox:
                    item.set(w.isChecked())

        sounds = AppSettings().sounds
        sounds['time_1'].set([0, self.SoundFinalEdit.path()])
        sounds['time_2'].set([self.SoundFirstSpinbox.value(),
                              self.SoundFirstEdit.path()])
        sounds['time_3'].set([self.SoundSecondSpinbox.value(),
                              self.SoundSecondEdit.path()])

        AppSettings().save()
