# encoding=utf-8
__author__ = "Aaron Randreth"
__copyright__ = "Copyright 2015+, Consortium MonPaGe"
__license__ = "Creative Commons 4.0 By-Nc-Sa"
__maintainer__ = "Roland Trouville"
__email__ = "contact.monpage@gmail.com"
__status__ = "Production"

from cotation.acoustic.display.summary_tree import SummaryTree

try:
	from typing import override
except ImportError:
	from typing_extensions import override  # noqa: F401
from datetime import datetime

from typing import Any, Callable, Optional
from PySide6.QtWidgets import (
	QPushButton,
	QVBoxLayout,
	QWidget,
)


class SummaryTab(QWidget):
	"""
	A QWidget that displays a summary of the cotation process and provides a button to finalize it.

	This tab contains a `SummaryTree` widget summarizing the progress/status of different steps
	and a button that allows the user to end the cotation process. An optional callback can be set
	to handle the quit action when the button is clicked.

	Attributes:
	    step_recap (SummaryTree): A tree widget showing step summaries.
	    _quit_cotation_callback (Optional[Callable[[], Any]]): Callback invoked when quitting cotation.
	"""

	step_recap: SummaryTree
	_quit_cotation_callback: Optional[Callable[[], Any]]

	def __init__(self, step_recap: SummaryTree):
		super().__init__()
		self.step_recap = step_recap
		self._quit_cotation_callback = None

		layout = QVBoxLayout()
		layout.addWidget(self.step_recap)

		quit_cotation = QPushButton("Terminer la cotation")
		quit_cotation.clicked.connect(self._handle_quit_cotation)
		layout.addWidget(quit_cotation)

		self.setLayout(layout)

	def update(self, step_idx: int, status: bool, when: Optional[datetime] = None):
		"""
		Updates the step recap with the given step index, status, and optional timestamp.

		Parameters:
			step_idx (int): The index of the step to update.
			status (bool): The status associated with the step.
			when (Optional[datetime]): Optional datetime indicating when the update occurred.

		Returns:
			None
		"""
		self.step_recap.update(step_idx, status, when)

	def set_quit_cotation_callback(self, callback: Callable[[], Any]) -> None:
		"""
		Sets the callback function to be called when quitting the cotation process.

		Parameters:
			callback (Callable[[], Any]): A function with no arguments to handle the quit event.

		Returns:
			None
		"""
		self._quit_cotation_callback = callback

	def _handle_quit_cotation(self) -> None:
		"""
		Invokes the quit cotation callback if it has been set.

		Returns:
			None
		"""
		if self._quit_cotation_callback:
			self._quit_cotation_callback()
