# encoding=utf-8
"""
file for the CotationWindow top object
"""

__author__ = "Roland Trouville"
__copyright__ = "Copyright 2015+, Consortium MonPaGe"
__license__ = "Creative Commons 4.0 By-Nc-Sa"
__maintainer__ = "Roland Trouville"
__email__ = "contact.monpage@gmail.com"
__status__ = "Production"

from PySide6.QtCore import Qt
from PySide6.QtGui import QKeySequence, QShortcut
from PySide6.QtWidgets import (
	QAbstractItemView,
	QLabel,
	QPushButton,
	QTreeWidget,
	QTreeWidgetItem,
	QWidget,
)

from tools.csv_manager import CSVManager
from tools.display_tools import DisplayTools


class PassationAdvancedWindow(QWidget):
	parent = None
	module_name = None
	participant_name = None
	filename = None
	stimuli_list = None
	values = []

	def __init__(self, parent, filename, module_name, participant_name):
		super(PassationAdvancedWindow, self).__init__()
		self.parent = parent
		self.filename = filename
		self.participant_name = participant_name
		self.module_name = module_name
		self.init_ui()
		self.init_values()

	def init_ui(self):
		"""
		Initializes the user interface for the advanced module start window.

		- Sets window size and layout.
		- Configures the stimuli list widget with three columns for display and selection.
		- Adds instructional label and a start button to trigger the module.
		- Binds the Escape key to cancel the start.
		- Sets the window title and shows the window.
		"""
		self.setGeometry(80, 80, 600, 400)
		self.setFixedSize(600, 400)

		self.stimuli_list = QTreeWidget(self)
		self.stimuli_list.setColumnCount(3)
		self.stimuli_list.setColumnWidth(0, 15)
		self.stimuli_list.setColumnWidth(1, 140)
		self.stimuli_list.setColumnWidth(2, 390)
		self.stimuli_list.setHeaderLabels(["#", "Type", "Valeur"])
		self.stimuli_list.resize(570, 340)
		self.stimuli_list.move(5, 15)
		self.stimuli_list.setSelectionMode(
			QAbstractItemView.SelectionMode.ExtendedSelection
		)

		tmp = QLabel("Séléctionnez les éléments que VOUS NE VOULEZ PAS utiliser", self)
		tmp.move(15, 360)
		tmp.resize(340, 25)
		DisplayTools.set_font_size(tmp, "lab_demadv_explication")

		tmp = QPushButton("Démarrer", self)
		tmp.move(480, 360)
		tmp.resize(100, 25)
		DisplayTools.set_font_size(tmp, "lab_demadv_gobtn")
		tmp.clicked.connect(self.launch_module)

		QShortcut(QKeySequence(Qt.Key.Key_Escape), self).activated.connect(
			self.cancel_advanced_start
		)

		self.setWindowTitle(
			"MonPaGe Passation - " + self.module_name + " - Démarrage Avancé"
		)

		self.show()

	def init_values(self):
		"""
		Loads stimulus data from a CSV file and populates the QTreeWidget with each item.

		- Reads tab-separated values from the specified module file.
		- Clears any existing items in the stimuli list.
		- Adds each stimulus or consigne item to the list with an index and label.
		"""
		self.values = CSVManager.read_file("./data/module/" + self.filename, "\t", -1)
		self.stimuli_list.clear()
		for i in range(1, len(self.values)):
			val = self.values[i]
			current_dir_treeitem = QTreeWidgetItem(0)
			lab = "Consigne"
			if val[0] == "s":
				lab = "Stimuli"
			current_dir_treeitem.setText(0, str(i))
			current_dir_treeitem.setText(1, lab)
			current_dir_treeitem.setText(2, val[3])
			self.stimuli_list.addTopLevelItem(current_dir_treeitem)

	def launch_module(self):
		"""
		Launches the module after filtering out user-deselected stimuli.

		- Collects the list of items the user has marked as unwanted.
		- Filters the initial values to exclude these items.
		- Passes the filtered values to the parent module for execution.
		"""
		selected_vals = self.stimuli_list.selectedItems()
		unwanted = []
		for v in selected_vals:
			unwanted.append(int(v.text(0)))

		values = []
		for i in range(0, len(self.values)):
			if i not in unwanted:
				values.append(self.values[i])

		self.parent.play_module_from_advanced_start(
			self.participant_name, self.module_name, values
		)

	def closeEvent(self, event):
		"""
		Handles the window close event by invoking the cancellation of the advanced start process.

		Delegates to `cancel_advanced_start()` to ensure proper cleanup and UI behavior.
		"""
		self.cancel_advanced_start()

	def cancel_advanced_start(self):
		"""
		Cancels the advanced module start process.

		- Closes the current window.
		- Shows the parent window again to return to the previous state.
		"""
		# noinspection PyUnresolvedReferences
		self.parent.show()
		self.close()
