import os


class StartupStatus:
    def __init__(self, title="INITIALISING"):
        self.title = title
        self._matrix = None
        self._canvas = None
        self._graphics = None
        self._font = None
        self._colour = None
        self._bar_colour = None
        self._ready = False
        self._init_matrix()

    def _init_matrix(self):
        if os.environ.get("PLANE_TRACKER_NO_MATRIX"):
            return
        try:
            from rgbmatrix import RGBMatrix, RGBMatrixOptions, graphics
            from setup import fonts
            import config

            options = RGBMatrixOptions()
            options.hardware_mapping = "adafruit-hat-pwm" if config.HAT_PWM_ENABLED else "adafruit-hat"
            options.rows = 32
            options.cols = 64
            options.chain_length = max(1, min(2, int(config.PANEL_COUNT or 2)))
            options.parallel = 1
            options.gpio_slowdown = config.GPIO_SLOWDOWN
            options.brightness = config.BRIGHTNESS
            options.disable_hardware_pulsing = True
            options.drop_privileges = False
            self._matrix = RGBMatrix(options=options)
            self._canvas = self._matrix.CreateFrameCanvas()
            self._graphics = graphics
            self._font = fonts.extrasmall
            self._colour = graphics.Color(255, 255, 255)
            self._bar_colour = graphics.Color(0, 133, 173)
            self._ready = True
        except Exception:
            self._ready = False

    def show(self, message, percent=None):
        text = f"{self.title}: {message}"
        if percent is not None:
            text += f" {int(percent)}%"
        print(text)
        if not self._ready:
            return

        width = self._canvas.width
        self._canvas.Clear()
        self._graphics.DrawText(self._canvas, self._font, 1, 8, self._colour, self.title[: width // 4])
        self._graphics.DrawText(self._canvas, self._font, 1, 18, self._colour, str(message)[: width // 4])
        if percent is not None:
            pct = max(0, min(100, int(percent)))
            bar_width = max(0, int((width - 2) * pct / 100))
            for x in range(1, 1 + bar_width):
                self._canvas.SetPixel(x, 27, self._bar_colour.red, self._bar_colour.green, self._bar_colour.blue)
        self._canvas = self._matrix.SwapOnVSync(self._canvas)

    def close(self):
        if self._ready:
            self._canvas.Clear()
            self._canvas = self._matrix.SwapOnVSync(self._canvas)
