from typing import Optional, Union
from PySide6.QtWidgets import (
	QLabel,
)

from cotation.acoustic.display.io_widget.io_widget import IOWidget


class Output(QLabel):
	label: str
	unit: str
	value: Optional[Union[float, int]]
	nb_significant_digits: int

	def __init__(self, label: str, unit: str, nb_significant_digits: int = 3):
		super().__init__()
		self.io_widget = IOWidget()

		self.label = label
		self.unit = unit
		self.value = None
		self.nb_significant_digits = nb_significant_digits

		self.update_value(None)
		self.setWordWrap(True)

	def update_value(self, value: Optional[Union[float, int]]):
		"""
		Updates the widget's display with a new numeric value.

		If `value` is None, displays "N/A" to indicate that no value is available.
		Otherwise, rounds the value to the configured number of significant digits
		and updates the display text including the unit.

		:param value: The numeric value to display (float or int), or None if unavailable.
		:type value: Optional[Union[float, int]]
		"""
		if value is None:
			self.setText(
				f"{self.io_widget.bolded_underlined_richtext(self.label)}: N/A {self.unit}"
			)
			return

		self.value = value

		display_value = round(value, self.nb_significant_digits)
		self.setText(
			f"{self.io_widget.bolded_underlined_richtext(self.label)}: {display_value} {self.unit}"
		)
