# 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 typing import Optional

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

from PySide6.QtWidgets import (
	QTreeWidget,
	QTreeWidgetItem,
)


class SummaryTree(QTreeWidget):
	"""
	A tree widget that displays a list of steps with their validation status and last modification date.

	Each step is represented as a row with three columns:
	    - Step name
	    - Status ("Oui" if validated, empty otherwise)
	    - Last modification timestamp (relative or absolute)

	Attributes:
	    None explicitly declared, but inherits from QTreeWidget.
	"""

	def __init__(
		self,
		steps: list[str],
		status: Optional[list[bool]] = None,
		when: Optional[list[datetime]] = None,
	):
		super().__init__()
		self.setColumnCount(2)
		self.setHeaderLabels(["Étape", "Validé", "Dernière Modification"])
		# self.setHeaderLabels(["Étape", "Validé"])

		for i in range(0, len(steps)):
			# for s in steps:
			s = steps[i]
			step = QTreeWidgetItem()
			step.setText(0, s)
			try:
				if status is not None and status[i]:
					step.setText(1, "Oui")
				else:
					step.setText(1, "")
			except IndexError:
				step.setText(1, "")
			try:
				if when is not None and isinstance(when[i], datetime):
					step.setText(2, self.format_entry_date_value(when[i]))
				else:
					step.setText(2, "")
			except IndexError:
				step.setText(2, "")

			self.addTopLevelItem(step)

		self.resizeColumnToContents(0)

	def update(self, step_idx: int, status: bool, when: Optional[datetime] = None):
		"""
		Update the status and timestamp of a specific step identified by 'step_idx'.

		Parameters:
		- step_idx: Index of the step to update.
		- status: Boolean indicating the completion status of the step.
		- when: Optional datetime object representing when the step was updated.

		Sets the status text to "Oui" if True, otherwise leaves it blank.
		Formats and displays the timestamp if provided.
		"""
		step = self.topLevelItem(step_idx)

		status_text = ""  # Todo localise correctly
		if status:
			status_text = "Oui"

		step.setText(1, status_text)
		if when is not None:
			step.setText(2, self.format_entry_date_value(when))

	@staticmethod
	def format_entry_date_value(when: datetime, absolute: bool = False) -> str:
		"""
		Format a datetime object as a string.

		If 'absolute' is False, returns a relative time description (e.g., "less than a minute ago", "less than X minutes/hours ago").
		If 'absolute' is True or the date is older than 48 hours, returns the date formatted as 'dd/mm/YYYY HH:MM:SS'.

		Returns an empty string if 'when' is None or not a datetime instance.
		"""
		if when is None or not isinstance(when, datetime):
			return ""
		if not absolute:
			diff = datetime.now() - when
			diff_in_s = diff.total_seconds()
			if diff_in_s < 60:
				return "Il y a moins d'une minute"
			if diff_in_s < 60 * 60:
				return "Il y a moins de {0} minute(s)".format(round(diff_in_s / 60.0))
			if diff_in_s < 3600 * 48:
				return "Il y a moins de {0} heure(s)".format(round(diff_in_s / 3600.0))
		return when.strftime("%d/%m/%Y %H:%M:%S")
