# 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.QtCore import QDir
from PySide6.QtWidgets import (
	QFileDialog,
	QGroupBox,
	QLabel,
	QProgressBar,
	QPushButton,
	QWidget,
)

from tools.display_tools import DisplayTools
from tools.general_tools import GeneralTools
from tools.migration_tools import MigrationTools


class ResultsMergingWindow(QWidget):
	parent = None
	input_dir = None
	fuse_btn = None
	pbar = None

	def __init__(self, parent):
		super(ResultsMergingWindow, self).__init__()
		self.parent = parent
		self.init_ui()

		self.show()

	def init_ui(self):
		"""
		Initializes the user interface of the window.

		Sets up the main window size and title, creates and positions
		labels, buttons, progress bar, and group box components with
		their respective properties and event connections.

		UI elements include:
		- Group box for selecting the directory containing .db files
		- Labels explaining the process and instructions
		- Button to browse and select the input directory
		- Progress bar to show operation progress
		- Button to start the merging process (disabled initially)

		:return: None
		"""
		self.setGeometry(80, 80, 500, 350)
		self.setFixedSize(500, 350)
		self.setWindowTitle("MonPaGe Export pour Praat")
		# self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)

		gtmp = QGroupBox("Répertoire contenant les .db", self)
		gtmp.resize(460, 30)
		gtmp.move(10, 10)

		self.input_dir = QLabel("", gtmp)
		self.input_dir.resize(400, 20)
		self.input_dir.move(10, 10)

		tmp = QPushButton("...", gtmp)
		tmp.move(410, 10)
		tmp.resize(40, 20)
		tmp.setToolTip("Choisir le répertoire source")
		DisplayTools.set_font_size(tmp, "lab_export_browsebtn")
		tmp.clicked.connect(self.change_input_folder)

		tmp = QLabel(
			"Choisissez un répertoire qui contient tous les fichiers .db à fusionner (directement dans le répertoire "
			"ou dans des sous-répertoires)",
			self,
		)
		tmp.setWordWrap(True)
		tmp.resize(400, 40)
		tmp.move(5, 50)
		tmp = QLabel('Un sous répertoire "results_merging" va être crée.', self)
		tmp.setWordWrap(True)
		tmp.resize(400, 20)
		tmp.move(5, 90)
		tmp = QLabel(
			"Dans ce sous répertoire, vous retrouverez une arborescence de participants, avec, dans chacun de ces répertoire, un fichier cotation_result.db",
			self,
		)
		tmp.setWordWrap(True)
		tmp.resize(400, 40)
		tmp.move(5, 110)
		tmp = QLabel(
			"Vous pourrez alors remettre ces fichiers dans le répertoire participant correspondant dans votre data/ de MonPaGe",
			self,
		)
		tmp.setWordWrap(True)
		tmp.resize(400, 40)
		tmp.move(5, 150)
		tmp = QLabel("Pensez à en faire une sauvegarde avant !", self)
		tmp.setWordWrap(True)
		tmp.resize(400, 20)
		tmp.move(5, 210)

		self.pbar = QProgressBar(self)
		self.pbar.move(5, 315)
		self.pbar.setTextVisible(False)
		self.pbar.resize(370, 25)

		self.fuse_btn = QPushButton("Fusionner", self)
		self.fuse_btn.move(380, 315)
		self.fuse_btn.resize(100, 25)
		self.fuse_btn.setEnabled(False)
		DisplayTools.set_font_size(self.fuse_btn, "lab_export_gobtn")
		self.fuse_btn.clicked.connect(self.fuse_results)

	def change_input_folder(self):
		"""
		Opens a directory selection dialog for the user to choose a folder.

		Updates the input directory label with the selected path and
		enables the 'Fuse' button if a valid directory is chosen.

		:return: None
		"""
		filename = QDir.toNativeSeparators(
			QFileDialog.getExistingDirectory(
				self, "Select Directory", self.input_dir.text()
			)
		)
		if filename != "":
			self.input_dir.setText(filename)
			self.fuse_btn.setEnabled(True)

	# PreferencesTools.set_preference_value("results_fusion_pref_path", filename)

	def fuse_results(self):
		"""
		Perform the merging of all cotation databases found in the selected directory.

		Checks if the target directory exists and is accessible. If not, displays an alert.
		Then calls the merging function and shows a confirmation alert upon success.

		:return: False after completion.
		"""
		target_dir = str(self.input_dir.text())
		if not os.path.isdir(target_dir):
			GeneralTools.alert_box(
				self, None, "Le répertoire choisi n'existe pas ou est inaccessible"
			)
			return

		r = MigrationTools.merge_all_cotation_dbs(target_dir, self.pbar)
		if r:
			GeneralTools.alert_box(
				self,
				"Fusion terminée",
				"Les résultats ont été fusionnés depuis " + target_dir,
			)

		return False
