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


import os
import shlex

from PySide6.QtGui import QIcon
from PySide6.QtWidgets import (
	QAbstractItemView,
	QGroupBox,
	QLabel,
	QLineEdit,
	QPushButton,
	QTreeWidget,
	QTreeWidgetItem,
	QWidget,
)

from reporting.pdf_reporting import IndicatorReporting, PDFReporting
from tools.display_tools import DisplayTools
from tools.general_tools import GeneralTools
from tools.options import Options
from tools.ui_tools import UITools


class ReportingWindow(QWidget):
	participant_list = None

	mods = None
	sessions = None
	module_off = {}
	module_simple = {}
	module_full = {}
	session_list = None
	reporting_btn = None
	export_btn = None

	participant_code = None
	judge_code = None
	session_date = None
	modules = [
		"Intelligibilite",
		"PneumoPhonatoire",
		"PseudoMots",
		"Diadoco",
		"Phrases",
		"Texte",
	]

	result_image = None

	def __init__(self, parent):
		super(ReportingWindow, self).__init__()
		self.judge_name = QLineEdit("", self)
		self.parent = parent
		self.init_ui()
		# self.load_participant_list()
		# self.load_script_list()
		self.show()

	def init_ui(self):
		"""
		Initialize the UI
		We base our design on a 800*600 window, and will automatically adapt it to actual window size
		:return: None
		"""
		# self.setGeometry(80, 80, 800, 600)
		self.setFixedSize(DisplayTools.size(420, 150))
		self.setWindowTitle("MonPaGe Rapport")
		# self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)

		self.participant_list = DisplayTools.generate_participant_dropdown(self)
		self.participant_list.resize(DisplayTools.size(200, 20))
		self.participant_list.move(DisplayTools.coord(10, 20))

		tmp = QLabel("Code du Juge", self)
		tmp.move(DisplayTools.coord(10, 50))
		tmp.resize(DisplayTools.size(70, 20))
		DisplayTools.set_font_size(tmp, "lab_code_juge")
		self.judge_name.move(DisplayTools.coord(90, 50))
		self.judge_name.resize(DisplayTools.size(100, 20))

		tmp = QPushButton("Valider", self)
		tmp.resize(DisplayTools.size(100, 20))
		tmp.move(DisplayTools.coord(110, 75))
		# choose_participant
		tmp.clicked.connect(self.choose_participant)

		self.sessions = QGroupBox("Sessions", self)
		self.sessions.move(DisplayTools.coord(210, 10))
		self.sessions.resize(DisplayTools.size(200, 90))
		self.sessions.setEnabled(False)

		self.session_list = QTreeWidget(self.sessions)
		self.session_list.setSelectionMode(
			QAbstractItemView.SelectionMode.SingleSelection
		)
		self.session_list.setColumnCount(1)
		self.session_list.setColumnWidth(0, DisplayTools.w(100))
		self.session_list.setHeaderLabels(["Session"])

		self.session_list.resize(DisplayTools.size(190, 70))
		self.session_list.move(DisplayTools.coord(5, 15))

		self.reporting_btn = QPushButton("Lancer le rapport", self)
		self.reporting_btn.resize(DisplayTools.size(150, 20))
		self.reporting_btn.move(DisplayTools.coord(250, 120))
		self.reporting_btn.setEnabled(False)
		self.reporting_btn.clicked.connect(self.launch_reporting)

		self.export_btn = QPushButton("Export TXT", self)
		self.export_btn.resize(DisplayTools.size(100, 20))
		self.export_btn.move(DisplayTools.coord(140, 120))
		self.export_btn.setEnabled(False)
		self.export_btn.clicked.connect(self.export_reporting)
		if not Options.is_enabled(Options.Option.RESEARCH):
			self.export_btn.setVisible(False)

		self.setWindowIcon(QIcon("./ui/icons/icon.png"))

	# tmp = QScrollArea(self)
	# tmp.move(DisplayTools.coord(10, 100))
	# tmp.resize(DisplayTools.size(780, 480))
	# tmp.setFixedHeight(DisplayTools.h(480))
	# tmp.setFixedWidth(DisplayTools.w(780))

	# self.result_image = QLabel()
	# self.result_image.move(DisplayTools.coord(1, 1))
	# tmp.setWidget(self.result_image)

	def load_session_list(self):
		"""
		Loads the list of sessions for the current participant into the session list UI.

		This method clears the current session list and repopulates it by scanning the
		participant's data directory for session folders. It also enables related UI
		controls if a participant code is set.

		Behavior:
			- Clears the existing session list.
			- If no participant code is set, returns False.
			- Enables the session selection and reporting/export buttons.
			- Checks the participant's data directory for session subdirectories.
			- For each valid session directory, adds an item to the session list UI.
			- The check for 'has_cotation' is currently a placeholder and always True.

		Returns:
			bool: False if participant_code is None, otherwise None.
		"""
		self.session_list.clear()
		if self.participant_code is None:
			return False

		# self.mods.setEnabled(True)
		self.sessions.setEnabled(True)
		self.reporting_btn.setEnabled(True)
		self.export_btn.setEnabled(True)

		base_path = "./data/participant/" + self.participant_code + "/"
		if not os.path.isdir(base_path):
			return

		for session in os.listdir(base_path):
			session_dir = os.path.join(base_path, session)
			if not os.path.isdir(session_dir):
				continue

			has_cotation = True  # TODO Refine this
			if not has_cotation:
				return

			current_dir_treeitem = QTreeWidgetItem(0)
			current_dir_treeitem.setText(0, session)
			self.session_list.addTopLevelItem(current_dir_treeitem)

	def choose_participant(self):
		"""
		Sets the current participant and judge codes based on the UI selections, then loads
		the sessions for the selected participant.

		Steps:
			- Extracts the participant code from the currently selected participant list item.
			- Retrieves and formats the judge code from the input field.
			- Validates that a judge code has been entered; if not, displays an alert and aborts.
			- Calls `load_session_list` to refresh the sessions related to the selected participant.
		"""
		tmp = str(self.participant_list.currentText()).split("-")[0]
		self.participant_code = tmp.strip()
		self.judge_code = self.judge_name.text().strip().upper()
		if self.judge_code == "" or self.judge_code is None:
			GeneralTools.alert_box(
				self, "Vous devez saisir un code de juge pour continuer"
			)
			return

		self.load_session_list()

	def export_reporting(self):
		"""
		Initiates the export process by calling do_reporting with PDF generation disabled.

		Returns:
			bool: Result of the export operation (success or failure).
		"""
		return self.do_reporting(False)

	def launch_reporting(self):
		"""
		Initiates the report generation process by calling do_reporting with PDF generation enabled.

		Returns:
			bool: Result of the report generation operation (success or failure).
		"""
		return self.do_reporting(True)

	def do_reporting(self, pdf=True):
		"""
		Generates or exports a report based on the selected session and user inputs.

		Args:
			pdf (bool): If True, generate a PDF report. If False, export data to a file.

		Returns:
			bool or None: True if operation succeeded, False if failed, or None if aborted due to validation.
		"""
		sessions = self.session_list.selectedItems()
		if len(sessions) != 1:
			GeneralTools.alert_box(
				self,
				"Vous devez selectionner une et une seule session pour faire le rapport",
			)
			return
		try:
			session_date = sessions[0].text(0)
			tmp = PDFReporting(self.participant_code, session_date, self.judge_code)
			if pdf:
				file = IndicatorReporting.get_reporting_filename()
				ok = tmp.do_reporting()
			else:
				file = IndicatorReporting.get_exporting_filename()
				ok = tmp.do_exporting(file)
			if not ok:
				GeneralTools.alert_box(
					self,
					"La création du rapport a echoué. Vérifiez que le fichier de rapport "
					+ file
					+ " que vous essayez de créer n'est pas déjà ouvert par une autre application",
				)

				return
			else:
				GeneralTools.alert_box(
					self, "Le rapport a été crée dans le fichier " + file
				)
			try:
				if Options.is_windows():
					fullpath = Options.get_base_dir() + "/" + file
					fullpath = os.path.normpath(fullpath)
					if " " not in fullpath:
						os.system("start " + fullpath)
					else:
						GeneralTools.alert_box(
							self,
							"Le chemin "
							+ fullpath
							+ " du rapport contient un espace, impossible d'ouvrir "
							"automatiquement le fichier de rapport. Veuillez le faire manuellement.",
						)
				if Options.is_mac():
					fullpath = Options.get_base_dir() + "/" + file
					fullpath = fullpath.replace("./", "")
					os.system("open " + shlex.quote(fullpath + "/" + file))
			except Exception as e:
				UITools.error_log(e, "erreur dans do_reporting")
		except Exception as e:
			UITools.error_log(e, "erreur dans do_reporting")
