# encoding=utf-8
"""
File for the CotationPhrasesWindow class. This class is used to do the cotation for phrases module
"""

__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
import random

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

from cotation.cotation_questions import CotationQuestionsWindow
from tools.display_tools import DisplayTools
from tools.general_tools import GeneralTools
from tools.migration_tools import MigrationTools


class CotationPhrasesWindow(CotationQuestionsWindow):
	"""
	The class to manage the window in the ModulePhrases cotation
	"""

	stimuli_group = []
	question_height = 55

	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.scroll_area = QScrollArea(self)
		self.stimuli_group = []
		self.init_cotation()
		self.init_participant_result_db()
		self.init_ui()

		self.display_cotation()

	def init_ui(self):
		"""
		Initialize the UI
		:return: None
		"""
		super().init_ui()
		self.form = QGroupBox("cotation", self)
		self.form.move(DisplayTools.coord(10, 10))
		self.save_button = QPushButton("Enregistrer", self.form)

		self.scroll_area.resize(DisplayTools.size(780, 580))
		self.scroll_area.setFixedHeight(DisplayTools.h(580))
		self.scroll_area.setFixedWidth(DisplayTools.w(780))
		self.scroll_area.move(DisplayTools.coord(10, 10))
		self.scroll_area.setWidget(self.form)

		self.save_button.resize(DisplayTools.size(120, 30))
		self.save_button.clicked.connect(self.save)

	def init_cotation(self):
		"""
		Initialise the cotation by doing two things : loading the cotation main database and filling the file_list
		list with the files found for this module
		:return:
		"""
		super().init_cotation()
		self.file_list = []
		stimuli = self.get_stimuli_with_questions("ModulePhrases")

		if os.path.isdir(self.directory_path):
			for filename in os.listdir(self.directory_path):
				if not filename.endswith("TextGrid"):
					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)
					else:
						msg = (
							"Un fichier d'enregistrement à été trouvé qui ne correspond pas a un stimuli prévu dans la "
							"base de donnée de cotation : " + filename
						)
						ok = MigrationTools.rename_laurie_question_2(
							self.participant_code
						)
						if ok:
							msg += (
								"\nLe problème a été corrigé automatiquement, merci de fermer la cotation du module et "
								""
								"de la relancer"
							)
						else:
							msg += "\nLe problème n'a pas pu être corrigé automatiquement, merci de contacter le support"
						GeneralTools.alert_box(self, msg)
			random.shuffle(
				self.file_list
			)  # We randomize the order of the stimuli so that judges won't be influenced

	def init_participant_result_db(self):
		"""
		Initialise or update the participant specific database for cotation
		:return:
		"""
		super().init_participant_result_db()

	def display_cotation(self):
		"""
		Display the cotation for the current item. In ModulePhrases, we don't have a current item per say,
		we in fact display cotation for all the items at once
		:return:
		"""
		i = 0
		for filename in self.file_list:
			stimuli_name = filename.split("_")[-1][:-4]
			tmp = self.get_questions_for_stimuli("ModulePhrases", stimuli_name)
			tmp_grp = self.make_questions_group(self.form, tmp, filename, module_name="ModulePhrases")
			tmp_grp.move(DisplayTools.coord(10, (i * self.question_height) + 15))
			self.stimuli.append(tmp_grp)
			i += 1

		self.save_button.move(
			DisplayTools.coord(630, ((i - 0) * self.question_height) + 20)
		)
		self.form.resize(DisplayTools.size(760, (i * self.question_height) + 60))

	def save(self):
		"""
		Save the choices made by the judge for the cotation
		:return:
		"""
		super().save()
		super().end_cotation()

	def listen_to_file(self):
		"""
		Will play audio file AND disable previously answered questions
		:return:
		"""

		sender = self.sender().parent()
		current_stimuli_id = int(str(sender.objectName()))

		# We disable all previous questions we had answer for
		found = False
		for gr in self.stimuli:
			stimuli_id = int(str(gr.objectName()))
			if stimuli_id == current_stimuli_id:
				found = True

			if not found:
				questions = gr.findChildren(QGroupBox)
				for ques in questions:
					val = None
					radios = ques.findChildren(QRadioButton)
					if len(radios) > 0:
						for rad in radios:
							if rad.isChecked():
								val = int(str(rad.objectName().split("_")[0]))
					else:  # We have no radio, maybe checkboxes
						val = 0
						checks = ques.findChildren(QCheckBox)
						for i in range(0, len(checks)):
							if checks[i].isChecked():
								val += pow(2, len(checks) - i - 1)

					if val is not None:
						# We have an answer, we deactivate the question
						gr.setEnabled(False)

		# filename = self.directory_path + str(sender.objectName())  # The filename is embeded in the button object name
		# AudioManager.play_wave(filename, None, None)

		super().listen_to_file()
