# -*- coding: utf-8 -*-
"""
LicenseStatusWidget_final.py
----------------------------
Drop-in Qt widget that live-displays the Mush3D license state.

It listens to the MUSH3D_LICENSE_VALID optionVar (set by C++ as an integer)
and updates a pill containing a colored dot + friendly status text:

    🟢 License: Active      ← VALID = 1
    🔴 License: Invalid     ← VALID = 0 or missing

The widget spins up protected scriptJobs to watch for changes in the optionVar,
ensuring live UI updates and blocking casual tampering. It auto-cleans on
hide/close to avoid zombie jobs.

Works with the custom qt shim imported via `from qt import …`.
"""


import maya.cmds as cmds
from qt import QtWidgets, QtCore, QtGui

class LicenseStatusWidget(QtWidgets.QWidget):
    OPT_VARS = {
        "VALID": "MUSH3D_LICENSE_VALID"
    }

    # Colors for the dot
    _GREEN = "#4caf50"      # Valid (active, non-trial)
    _YELLOW = "#ffc107"     # Trial (valid)
    _RED = "#f44336"        # Invalid or trial expired
    _GREY = "#9e9e9e"       # Unknown / uninitialized

    def __init__(self, parent=None):
        super().__init__(parent)
        self._job_ids = []

        # Build UI --------------------------------------------------
        lay = QtWidgets.QHBoxLayout(self)
        lay.setContentsMargins(6, 2, 6, 2)
        lay.setSpacing(6)

        # Colored dot
        self._dot = QtWidgets.QLabel()
        self._dot.setFixedSize(14, 14)
        self._dot.setStyleSheet(self._dot_style(self._GREY))
        lay.addWidget(self._dot, alignment=QtCore.Qt.AlignVCenter)

        # Text
        self._text = QtWidgets.QLabel("License: Unknown")
        f = self._text.font()
        f.setPointSize(9)
        self._text.setFont(f)
        lay.addWidget(self._text)

        lay.addStretch(1)

        # Ensure optionVars exist
        if not cmds.optionVar(exists=self.OPT_VARS["VALID"]):
            cmds.optionVar(iv=(self.OPT_VARS["VALID"], 0))

        self._refresh()
        self._start_jobs()

    # ------------------------------------------------------------------
    # ScriptJob glue
    # ------------------------------------------------------------------

    def _start_jobs(self):
        """Start protected scriptJobs for each optionVar."""
        self._stop_jobs()
        for var in self.OPT_VARS.values():
            job_id = cmds.scriptJob(
                optionVarChanged=[var, self._refresh], protected=True)
            self._job_ids.append(job_id)

    def _stop_jobs(self):
        """Kill all scriptJobs if they exist."""
        for job_id in self._job_ids:
            if cmds.scriptJob(exists=job_id):
                cmds.scriptJob(kill=job_id, force=True)
        self._job_ids = []

    # ------------------------------------------------------------------
    # Callback
    # ------------------------------------------------------------------

    def _refresh(self):
        """Check license status and update UI."""
        try:
            is_valid = cmds.optionVar(q=self.OPT_VARS["VALID"]) == 1
        except RuntimeError:
            is_valid = False

        if is_valid:
            text = "License: Active"
            color = self._GREEN
        else:
            text = "License: Invalid"
            color = self._RED

        self._dot.setStyleSheet(self._dot_style(color))
        self._text.setText(text)


    # ------------------------------------------------------------------
    # Helpers
    # ------------------------------------------------------------------

    @staticmethod
    def _dot_style(bg):
        return (
            f"background-color:{bg}; "
            "border-radius:7px;"
        )

    # ------------------------------------------------------------------
    # QWidget overrides – keep job lifecycle tidy
    # ------------------------------------------------------------------

    def closeEvent(self, evt):
        self._stop_jobs()
        super().closeEvent(evt)

    def hideEvent(self, evt):
        self._stop_jobs()
        super().hideEvent(evt)

    def showEvent(self, evt):
        super().showEvent(evt)
        if not self._job_ids:
            self._refresh()
            self._start_jobs()