"""Four-digit TM1650 display driver for CircuitPython on EDU PICO.

Use: from edu_pico_lib.TM1650Display import TM1650Display
The caller creates and releases the shared busio.I2C bus.
"""


class TM1650Display:
    """Control a four-digit module at I2C addresses 0x24 and 0x34-0x37."""

    _SEGMENTS = {
        "0": 0x3F, "1": 0x06, "2": 0x5B, "3": 0x4F, "4": 0x66,
        "5": 0x6D, "6": 0x7D, "7": 0x07, "8": 0x7F, "9": 0x6F,
        " ": 0x00, "-": 0x40,
    }
    _CONTROL_ADDRESS = 0x24
    _DIGIT_ADDRESS = 0x34

    def __init__(self, i2c, brightness=3):
        self._validate_brightness(brightness)
        self._i2c = i2c
        self._brightness = brightness
        self._enabled = False
        self.clear()
        self.on()

    @staticmethod
    def _validate_brightness(brightness):
        if type(brightness) is not int or not 1 <= brightness <= 7:
            raise ValueError("Brightness must be an integer from 1 to 7")

    def _write(self, address, value):
        while not self._i2c.try_lock():
            pass
        try:
            self._i2c.writeto(address, bytes((value,)))
        finally:
            self._i2c.unlock()

    def show(self, value):
        """Show four characters (digits, spaces, minus) or integer 0-9999.

        Integers are zero-padded. Short strings are right-aligned with spaces.
        Invalid values raise ValueError before any display write occurs.
        """
        if type(value) is int:
            if not 0 <= value <= 9999:
                raise ValueError("Number must be from 0 to 9999")
            text = "{:04d}".format(value)
        elif isinstance(value, str):
            if len(value) > 4 or any(c not in self._SEGMENTS for c in value):
                raise ValueError("Use at most four digits, spaces or minus signs")
            text = " " * (4 - len(value)) + value
        else:
            raise ValueError("Show an integer or a string")

        for position, character in enumerate(text):
            self._write(self._DIGIT_ADDRESS + position, self._SEGMENTS[character])
        if not self._enabled:
            self.on()

    def clear(self):
        """Blank all four digits without changing the enabled state."""
        for position in range(4):
            self._write(self._DIGIT_ADDRESS + position, 0x00)

    def on(self):
        """Enable the display at the selected brightness."""
        self._write(self._CONTROL_ADDRESS, (self._brightness << 4) | 0x01)
        self._enabled = True

    def off(self):
        """Disable the display; retain digit contents and the shared bus."""
        self._write(self._CONTROL_ADDRESS, 0x00)
        self._enabled = False

    def set_brightness(self, brightness):
        """Select level 1 (dimmest) to 7 (brightest); use off() to disable."""
        self._validate_brightness(brightness)
        control = (brightness << 4) | (1 if self._enabled else 0)
        self._write(self._CONTROL_ADDRESS, control)
        self._brightness = brightness
