# encoding=utf-8

__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,
	QPushButton,
	QRadioButton,
)

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


class CotationPneumoPhonatoireWindow(CotationQuestionsWindow):
	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.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)

	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 = []
		stimuli = self.get_stimuli_with_questions("ModulePneumoPhonatoire")

		if os.path.isdir(self.directory_path):
			for filename in os.listdir(self.directory_path):
				stimuli_name = filename.split("_")[-1][:-4]
				if not filename.endswith("TextGrid") and stimuli_name in stimuli:
					self.file_list.append(filename)

	# 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]

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

		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.current_file_index += 1
		if self.current_file_index >= len(self.file_list):  # next item or end
			super().end_cotation()
		else:
			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()
