# encoding=utf-8
"""
File for the CotationTexteWindow class
"""

__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"

import os

from PySide6.QtWidgets import (
	QApplication,
	QCheckBox,
	QGroupBox,
	QLabel,
	QPushButton,
	QRadioButton,
)

from cotation.cotation_questions import CotationQuestionsWindow
from tools.display_tools import DisplayTools


class CotationTexteWindow(CotationQuestionsWindow):
	"""
	Used to display a window to do cotation for ModuleTexte files
	"""

	file_navigation_list = None
	file_state_list: dict[str, bool]

	cotation_img: QLabel

	def __init__(
		self,
		parent,
		participant_code,
		module_name,
		judge_code,
		session_path,
		advanced_mode=False,
	):
		super().__init__(
			parent,
			participant_code,
			module_name,
			judge_code,
			session_path,
			advanced_mode,
		)
		self.file_navigation_list = None
		self.file_state_list = {}
		self.init_cotation()
		self.init_participant_result_db()
		self.current_file_index = 0
		self.init_ui()
		self.display_current_item_cotation()

	def init_ui(self):
		"""
		Initialize the UI
		:return: None
		"""
		super().init_ui()

		self.form = QGroupBox("Cotation", self)
		self.form.resize(DisplayTools.size(780, 580))
		self.form.move(DisplayTools.coord(10, 10))

		tmp = QPushButton("Enregistrer et continuer", self.form)
		tmp.move(DisplayTools.coord(540, 555))
		tmp.resize(DisplayTools.size(220, 20))
		DisplayTools.set_font_size(tmp, "lab_ctn_save_next")
		tmp.clicked.connect(self.save)

		self.cotation_img = QLabel("", self.form)
		self.cotation_img.resize(DisplayTools.size(750, 200))
		self.cotation_img.move(DisplayTools.coord(10, 350))

	# self.file_navigation_list = QTreeWidget(self.form)
	# self.file_navigation_list.setColumnCount(2)
	# self.file_navigation_list.setColumnWidth(0, 40)
	# self.file_navigation_list.setHeaderLabels(["", "Fichier"])
	#
	# self.file_navigation_list.move(610, 15)
	# self.file_navigation_list.resize(160, 500)

	# tmp = QPushButton("Coter le fichier", self.form)
	# tmp.move(610, 520)
	# tmp.resize(160, 20)
	# DisplayTools.set_font_size(tmp, "lab_ctn_goto_file")
	# tmp.clicked.connect(self.file_navigation_list_select)

	# self.init_file_navigation_list()

	def init_cotation(self):
		"""
		Initialize the cotation. Links to cotation main database and loads file_list with names of files for which we
		have questions in the database
		:return: None
		"""
		super().init_cotation()
		self.file_list = []
		self.file_state_list = {}
		# special : we do not want the file for which we have no question in db
		stimuli = self.get_stimuli_with_questions("ModuleTexte")

		wanted_order = ["lundi", "dimanche", "mardi", "jeudi", "vendredi", "samedi2"]
		if os.path.isdir(self.directory_path):
			for wanted in wanted_order:
				for filename in os.listdir(self.directory_path):
					stimuli_name = filename.split("_")[-1][:-4]
					if (
						not filename.endswith("TextGrid")
						and stimuli_name in stimuli
						and stimuli_name == wanted
					):  # We only take files we found for which we
						# have data in the cotation main database. Others are rejected. Made to excluse .TextGrid
						# and such
						self.file_list.append(filename)

			# if os.path.isdir(self.directory_path):
			#     for filename in os.listdir(self.directory_path):
			#         stimuli_name = filename.split("_")[-1][:-4]
			#         if stimuli_name in stimuli:  # We only take files we found for which we have data in
			#             # the cotation main database. Others are rejected. Made to excluse .TextGrid
			# and such
			#             self.file_list.append(filename)

	def init_participant_result_db(self):
		"""
		Initialize the participant specific cotation database and populate the file_state_list array
		:return: None
		"""
		super().init_participant_result_db()
		results = self.get_available_results(
			self.session_path, self.participant_code, self.judge_code, "ModuleTexte"
		)
		for r in results:
			self.file_state_list[r[0]] = True

	# noinspection PyArgumentList
	def display_current_item_cotation(self):
		"""
		Display cotation for the current item
		:return: None
		"""
		if len(self.stimuli) > 0:
			for ques in self.stimuli:
				ques.setParent(None)  # remove questions created for previous item
		self.stimuli = []
		filename = self.file_list[self.current_file_index]

		# updating the filelist with selection
		# tmp = self.file_list[self.current_file_index].split("_")
		# w = self.file_navigation_list.findItems(tmp[-1], Qt.MatchContains, 1)  # we select the current item in the
		# # navigation list
		# if len(w) == 1:
		#     w[0].setSelected(True)

		self.form.setTitle("Cotation " + filename)
		stimuli_name = filename.split("_")[-1][:-4]
		tmp = self.get_questions_for_stimuli("ModuleTexte", stimuli_name)
		if len(tmp) > 0:
			tmp_grp = self.make_questions_group(self.form, tmp, filename, "ModuleTexte")
			tmp_grp.move(10, +15)
			tmp_grp.show()
			self.stimuli = [tmp_grp]

		DisplayTools.display_image(
			self.cotation_img,
			"./data/module/ModuleTexte/" + stimuli_name + "_cotation.png",
		)

		self.update()
		QApplication.processEvents()

	def save(self):
		"""
		Saving answers to questions
		:return: None
		"""
		super().save()
		f = self.file_list[self.current_file_index].split("_")
		self.file_state_list[f[len(f) - 1][:-4]] = True  # updating the file_state_list

		self.current_file_index += 1
		if self.current_file_index >= len(self.file_list):  # next item or end
			super().end_cotation()
		else:
			self.init_file_navigation_list()  # refreshing navigation list to update Xs
			self.display_current_item_cotation()

	def top_question_change(self):
		"""
		What to do when a top level question changes
		:return: None
		"""
		sender = self.sender()
		vals = sender.objectName().split(
			"_"
		)  # we have an object name like "value of answer"_"sub question id"
		val = int(vals[0])
		sub_question_id = int(vals[1])
		self.enable_sub_question(sub_question_id, val > 0)

	def enable_sub_question(self, qid, enabled):
		"""
		Enables or disables a sub question
		:param qid: id of the question to enable/disable
		:param enabled: True to enable, False to disable
		:return: None
		"""
		stimuli = self.form.findChildren(QGroupBox)
		for stim in stimuli:
			questions = stim.findChildren(QGroupBox)
			for ques in questions:
				question_id = int(str(ques.objectName()))
				if question_id == qid:
					ques.setEnabled(enabled)
					if not enabled:
						# We remove the values chosen
						radios = ques.findChildren(QRadioButton)
						for rad in radios:
							rad.setAutoExclusive(False)
							rad.setChecked(False)
							rad.setAutoExclusive(True)
						checks = ques.findChildren(QCheckBox)
						for chk in checks:
							chk.setChecked(False)

		self.update()
		QApplication.processEvents()

	def init_file_navigation_list(self):
		"""
		Initialize the navigation list with the filenames of the items in the module/session
		:return: None
		"""

	# self.file_navigation_list.clear()
	# for f in self.file_list:
	#     f = f.split("_")
	#     name = f[len(f) - 1]
	#     current_dir_treeitem = QTreeWidgetItem(0)
	#     current_dir_treeitem.setText(1, name)
	#     if name[:-4] in self.file_state_list:
	#         current_dir_treeitem.setText(0, "X")
	#     self.file_navigation_list.addTopLevelItem(current_dir_treeitem)

	def file_navigation_list_select(self):
		"""
		When we click on the button after selecting a file in the file navigation list - Changes WITHOUT SAVING
		:return: None
		"""


# filename = self.file_navigation_list.selectedItems()
# if len(filename) == 1:
#     tmp = filename[0].text(1)
#     for i in range(0, len(self.file_list)):
#         if self.file_list[i].endswith(tmp):  # Changin current file withjout saving
#             self.current_file_index = i
#             self.display_current_item_cotation()
#             return
