from nmreval.configs import config_paths
from nmreval.lib.colors import Colors, available_cycles

from ..Qt import QtWidgets, QtCore, QtGui
from .._py.color_palette import Ui_Dialog


class ColorDialog(QtWidgets.QDialog, Ui_Dialog):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.setupUi(self)

        self._palettes = available_cycles
        self.palette_combobox.addItems(self._palettes.keys())

        self.colorlist.installEventFilter(self)

    def eventFilter(self, src: QtCore.QObject, evt: QtCore.QEvent) -> bool:
        if evt.type() == evt.KeyPress:
            if evt.key() == QtCore.Qt.Key_Delete:
                self.colorlist.takeItem(self.colorlist.currentRow())

                return True

        return super().eventFilter(src, evt)

    @QtCore.pyqtSlot(name='on_add_palette_button_pressed')
    @QtCore.pyqtSlot(name='on_append_palette_button_pressed')
    def set_palette(self, clear: bool = False):
        if self.sender() == self.add_palette_button or clear:
            self.colorlist.clear()

        for color in self._palettes[self.palette_combobox.currentText()]:
            item = QtWidgets.QListWidgetItem(color.name)
            item.setData(QtCore.Qt.DecorationRole, QtGui.QColor.fromRgbF(*color.rgb(normed=True)))
            self.colorlist.addItem(item)

    @QtCore.pyqtSlot(name='on_add_color_button_pressed')
    def add_color(self):
        color = self.color_combobox.value
        item = QtWidgets.QListWidgetItem(color.name)
        item.setData(QtCore.Qt.DecorationRole, QtGui.QColor.fromRgbF(*color.rgb(normed=True)))
        self.colorlist.addItem(item)

    @QtCore.pyqtSlot(name='on_save_button_pressed')
    def save_new_palette(self):
        if not self.colorlist.count():
            _ = QtWidgets.QMessageBox.warning(self, 'Error', 'No colors to save.')
            return

        if not self.new_name_edit.text():
            _ = QtWidgets.QMessageBox.warning(self, 'Error', 'New list has no name.')
            return

        color_name = self.new_name_edit.text()  # type: str
        if color_name in self._palettes:
            _ = QtWidgets.QMessageBox.warning(self, 'Error', 'Name is already used.')
            return

        color_file = config_paths() / 'colors.cfg'

        new_palette = []
        with color_file.open('a') as f:
            f.write('#-- %s\n' % color_name)
            for i in range(self.colorlist.count()):
                item = self.colorlist.item(i)
                r, g, b = item.data(QtCore.Qt.DecorationRole).getRgbF()[:3]
                new_palette.append(Colors.from_rgb(r, g, b, normed=True))
                f.write(f'{r*255:.1f}, {g*255:.1f}, {b*255:.1f}\n')
            f.write('\n')

        self._palettes[color_name] = new_palette
        self.palette_combobox.addItem(color_name)

    def load_palette(self, name: str):
        idx = self.palette_combobox.findText(name)
        if idx != -1:
            self.palette_combobox.setCurrentIndex(idx)
            self.set_palette(clear=True)
