__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 logging
import traceback

from PySide6.QtGui import QColor, QPalette
from PySide6.QtWidgets import QGroupBox, QLabel, QProgressBar

logger = logging.getLogger(__name__)


class UITools(object):
	"""
	A utility class for managing UI elements and their dynamic behavior in the application.

	UITools provides static methods to manipulate key UI widgets such as progress bars,
	labels, and control groups. It supports updating visual elements during audio
	recording or playback, and handles error reporting in the user interface context.

	Responsibilities:
	- Control and update the audio progress bar and associated timer label.
	- Change visual indicators (e.g., palette colors) of the control group to reflect UI states.
	- Log and format exceptions for display or debugging.
	- Provide centralized access to common UI components.

	Attributes:
	    display_debug (Any): Reserved for future use or debugging display.
	    audioProgressBar (QProgressBar): The progress bar used to show audio playback or recording progress.
	    timerLabel (QLabel): The label used to display elapsed or remaining time.
	    controlGroup (QGroupBox): A UI container group whose appearance may be altered during recording.
	    controlGroupDefaultPalette (QPalette): The default color scheme of the control group.
	    controlGroupRecordPalette (QPalette): The red-colored palette used to indicate recording state.
	"""

	display_debug = None
	audioProgressBar = None
	timerLabel = None
	controlGroup = None
	controlGroupDefaultPalette = None
	controlGroupRecordPalette = None

	@staticmethod
	def set_audio_progressbar(pbar: QProgressBar = None):
		"""
		Set the audio progress bar widget used by UITools.

		Args:
			pbar (QProgressBar, optional): The progress bar widget to be updated. Defaults to None.
		"""
		UITools.audioProgressBar = pbar

	@staticmethod
	def set_timer_label(label: QLabel = None):
		"""
		Set the timer label widget used by UITools.

		Args:
			label (QLabel, optional): The label widget to display timer values. Defaults to None.
		"""
		UITools.timerLabel = label

	@staticmethod
	def on_val_changed(val: int):
		"""
		Update the audio progress bar value.

		Args:
			val (int): The new progress value to set.
		"""
		if UITools.audioProgressBar and UITools.audioProgressBar is not None:
			UITools.audioProgressBar.setValue(val)
			UITools.audioProgressBar.update()

	@staticmethod
	def on_max_changed(val: int):
		"""
		Update the maximum value of the audio progress bar.

		Args:
			val (int): The new maximum value to set.
		"""
		if UITools.audioProgressBar and UITools.audioProgressBar is not None:
			UITools.audioProgressBar.setMaximum(val)

	@staticmethod
	def on_timer_changed(val: float):
		"""
		Update the timer label text with a formatted float value.

		Args:
			val (float): The new timer value to display.
		"""
		if UITools.timerLabel and UITools.timerLabel is not None:
			UITools.timerLabel.setText("%6.2F" % val)

	@staticmethod
	def error_log(e: Exception, cont: str = ""):
		"""
		Log an exception with an optional context message and full traceback.

		Args:
			e (Exception): The exception to log.
			cont (str, optional): Additional context or message to prepend. Defaults to "".
		"""
		chaine = cont + " " + str(e)
		trace = traceback.format_tb(e.__traceback__)
		if trace is not None and len(trace) > 0:
			chaine += "\n" + "\n".join(trace)
		logger.error(chaine)

	@staticmethod
	def set_control_group(group: QGroupBox = None):
		"""
		Set the control group widget for UI highlighting and store its palettes.

		Also initializes a red palette for recording state if not already set.

		Args:
			group (QGroupBox, optional): The group box widget to manage. Defaults to None.
		"""
		UITools.controlGroup = group
		if UITools.controlGroup and UITools.controlGroup is not None:
			UITools.controlGroupDefaultPalette = group.palette()
			if UITools.controlGroupRecordPalette is None:
				UITools.controlGroupRecordPalette = QPalette()
				UITools.controlGroupRecordPalette.setColor(
					QPalette.ColorRole.Window, QColor(255, 0, 0)
				)
				UITools.controlGroupRecordPalette.setColor(
					QPalette.ColorRole.WindowText,
					group.palette().color(QPalette.ColorRole.WindowText),
				)

	@staticmethod
	def change_control_group_color(record: bool = True):
		"""
		Change the control group's color to indicate recording status.

		Uses a red palette for recording, otherwise resets to default.

		Args:
			record (bool, optional): True to set recording color, False to reset. Defaults to True.
		"""
		if UITools.controlGroup and UITools.controlGroup is not None:
			try:
				if record:
					UITools.controlGroup.setPalette(UITools.controlGroupRecordPalette)
				else:
					UITools.controlGroup.setPalette(UITools.controlGroupDefaultPalette)
			except RuntimeError:
				pass
			try:
				if UITools.audioProgressBar and UITools.audioProgressBar is not None:
					UITools.audioProgressBar.update()
			except RuntimeError:
				pass
