from PySide2 import QtWidgets as qtw
from PySide2 import QtCore as qtc

from db import Database
from factor_levels_dialog import *


# noinspection PyTypeChecker
class FactorLevels(qtw.QDialog):
    def __init__(self, parent, trial_id, factor_id, factor_title):
        super(FactorLevels, self).__init__(parent)
        self.parent = parent
        self.ui = Ui_FactorLevelsDialog()
        self.ui.setupUi(self)
        self.database = Database.get_instance(parent)
        self.trial_id = trial_id
        self.factor_id = factor_id
        self.setWindowTitle(self.tr('Levels of {}').format(factor_title))
        self.ui.addLevelPushButton.clicked.connect(self.add_level)
        self.ui.deleteLevelPushButton.clicked.connect(self.delete_level)
        self.ui.closePushButton.clicked.connect(self.close)
        self.ui.levelsTableWidget.cellChanged.connect(self.level_cell_changed)
        self.ui.levelsTableWidget.setSelectionBehavior(qtw.QAbstractItemView.SelectRows)
        self.ui.levelsTableWidget.setSelectionMode(qtw.QAbstractItemView.SingleSelection)
        self.load_levels()

    def add_level(self):
        if self.parent.check_trial_subjects_or_preload():
            return
        title, ok = qtw.QInputDialog.getText(
            self,
            self.tr('Level title'),
            self.tr('Title'),
            qtw.QLineEdit.EchoMode.Normal
        )
        if ok and len(title.strip()) != 0:
            if self.database.treatment_title_exists(title, self.factor_id):
                qtw.QMessageBox.critical(self,
                                            self.tr('Error!'),
                                            self.tr('''Level title '{}' already exist!'''.format(title))
                                            )
                return
            level_id = self.database.insert_level(self.trial_id, self.factor_id, title)
            state = self.ui.levelsTableWidget.blockSignals(True)
            r = self.ui.levelsTableWidget.rowCount()
            self.ui.levelsTableWidget.insertRow(r)
            id_item = qtw.QTableWidgetItem(str(level_id))
            id_item.setTextAlignment(qtc.Qt.AlignCenter)
            self.ui.levelsTableWidget.setCellWidget(r, 0, qtw.QLabel())
            self.ui.levelsTableWidget.setItem(r, 0, id_item)
            title_item = qtw.QTableWidgetItem(title)
            self.ui.levelsTableWidget.setItem(r, 1, title_item)
            self.ui.levelsTableWidget.blockSignals(state)

    def delete_level(self):
        if self.parent.check_trial_subjects_or_preload():
            return
        selected = self.ui.levelsTableWidget.selectedIndexes()
        if not selected:
            return
        title = self.ui.levelsTableWidget.item(selected[0].row(), 1).text()
        button = qtw.QMessageBox.question(self, self.tr("Confirm delete"),
                                          self.tr('Are you sure you want to delete "%s"?') % title,
                                          qtw.QMessageBox.Yes | qtw.QMessageBox.No)
        if button != qtw.QMessageBox.Yes:
            return
        level_id = int(self.ui.levelsTableWidget.item(selected[0].row(), 0).text())
        self.database.delete_level(level_id)
        self.ui.levelsTableWidget.blockSignals(True)
        self.ui.levelsTableWidget.removeRow(selected[0].row())
        self.ui.levelsTableWidget.blockSignals(False)

    def level_cell_changed(self, row, col):
        level_id = int(self.ui.levelsTableWidget.item(row, 0).text())
        title = self.ui.levelsTableWidget.item(row, col).text()
        oldValue = self.database.update_level(level_id, title)
        if oldValue is not None:
            self.parent.abort_table_widget_change(self.ui.levelsTableWidget, row, col, oldValue)

    def load_levels(self):
        self.ui.levelsTableWidget.blockSignals(True)
        self.ui.levelsTableWidget.setRowCount(0)
        self.ui.levelsTableWidget.setColumnCount(2)
        header = self.ui.levelsTableWidget.horizontalHeader()
        header.setSectionResizeMode(0, qtw.QHeaderView.ResizeToContents)
        header.setSectionResizeMode(1, qtw.QHeaderView.Stretch)
        self.ui.levelsTableWidget.setHorizontalHeaderLabels([self.tr('ID'), self.tr('Level')])
        query = self.database.load_levels(self.factor_id)
        while query.next():
            r = self.ui.levelsTableWidget.rowCount()
            self.ui.levelsTableWidget.insertRow(r)
            id_item = qtw.QTableWidgetItem(str(query.value('id')))
            id_item.setTextAlignment(qtc.Qt.AlignCenter)
            self.ui.levelsTableWidget.setCellWidget(r, 0, qtw.QLabel())
            self.ui.levelsTableWidget.setItem(r, 0, id_item)
            title_item = qtw.QTableWidgetItem(query.value('title'))
            self.ui.levelsTableWidget.setItem(r, 1, title_item)
        self.ui.levelsTableWidget.blockSignals(False)
