# -*- coding: utf-8 -*-
"""muLicenseDialog.py – FINAL
=============================
Tiny dialog that lets the user either:

* Paste a License Key → `cmds.muLicenseCmd(sn=<key>, activationType="online")`
* Enter IP + Port of an offline server → `cmds.muLicenseCmd(serverIp=<ip>, serverPort=<port>, activationType="server")`

Key features
------------
* Uses a Stacked-Widget controlled by two radio buttons (clean UI).
* Port default 57321 with a QIntValidator(1–65535) 
* Minimum dialog width 300 px so labels/fields never clip.
* Persists serial number, IP, and port in QSettings for reuse.
* Works in both PySide2/Qt5 (Maya 2022+) and PySide1/Qt4 (Maya 2018–2021).
"""

from qt import QtWidgets, QtCore, QtGui  # type: ignore
import maya.cmds as cmds


class LicenseDialog(QtWidgets.QDialog):
    SETTINGS_SN   = "MUSH_3D_UI_SERIAL_NUMBER"
    SETTINGS_IP   = "MUSH_3D_UI_SERVER_IP"
    SETTINGS_PORT = "MUSH_3D_UI_SERVER_PORT"

    def __init__(self, parent=None):
        super(LicenseDialog, self).__init__(parent)
        self.setWindowTitle("Apply Mush3D License")
        self.setWindowFlags(self.windowFlags() | QtCore.Qt.Tool)
        self.setMinimumWidth(300)

        # ---------- load persisted values -----------------------------
        sets = QtCore.QSettings()
        saved_sn   = sets.value(self.SETTINGS_SN,   u"", type=str)
        saved_ip   = sets.value(self.SETTINGS_IP,   u"", type=str)
        saved_port = sets.value(self.SETTINGS_PORT, u"57321", type=str)

        # ---------- radio buttons -------------------------------------
        key_radio = QtWidgets.QRadioButton("License Key")
        srv_radio = QtWidgets.QRadioButton("Offline Server")
        key_radio.setChecked(True)
        mode_grp = QtWidgets.QButtonGroup(self)
        mode_grp.addButton(key_radio, 0)
        mode_grp.addButton(srv_radio, 1)

        # ---------- stacked pages -------------------------------------
        stack = QtWidgets.QStackedWidget()

        # page 0 – key
        key_page = QtWidgets.QWidget()
        key_form = QtWidgets.QFormLayout(key_page)
        self._key_edit = QtWidgets.QLineEdit(saved_sn)
        self._key_edit.setPlaceholderText("Paste license key here…")
        key_form.addRow("Key:", self._key_edit)
        stack.addWidget(key_page)

        # page 1 – server
        srv_page = QtWidgets.QWidget()
        srv_form = QtWidgets.QFormLayout(srv_page)
        self._ip_edit = QtWidgets.QLineEdit(saved_ip)
        self._ip_edit.setPlaceholderText("192.168.0.10")
        self._port_edit = QtWidgets.QLineEdit(saved_port)
        self._port_edit.setValidator(QtGui.QIntValidator(1, 65535, self))
        self._port_edit.setMaximumWidth(80)
        srv_form.addRow("IP:", self._ip_edit)
        srv_form.addRow("Port:", self._port_edit)
        stack.addWidget(srv_page)

        mode_grp.buttonClicked.connect(lambda b: stack.setCurrentIndex(mode_grp.id(b)))

        # ---------- buttons -------------------------------------------
        apply_btn = QtWidgets.QPushButton("Apply")
        cancel_btn = QtWidgets.QPushButton("Cancel")
        apply_btn.clicked.connect(lambda: self._apply(mode_grp.checkedId()))
        cancel_btn.clicked.connect(self.reject)

        # ---------- layout --------------------------------------------
        main = QtWidgets.QVBoxLayout(self)
        row = QtWidgets.QHBoxLayout()
        row.addWidget(key_radio)
        row.addWidget(srv_radio)
        row.addStretch()
        main.addLayout(row)
        main.addWidget(stack)
        btn_row = QtWidgets.QHBoxLayout()
        btn_row.addStretch()
        btn_row.addWidget(apply_btn)
        btn_row.addWidget(cancel_btn)
        main.addLayout(btn_row)

    # -----------------------------------------------------------------
    def _apply(self, mode_id):
        sets = QtCore.QSettings()
        if mode_id == 0:  # key
            key = self._key_edit.text().strip()
            if not key:
                QtWidgets.QMessageBox.warning(self, "Oops", "Paste a license key first.")
                return
            cmds.muLicenseCmd(activationType="online", sn=key)
            # Persist serial number
            sets.setValue(self.SETTINGS_SN, key)
            sets.sync()
            QtWidgets.QMessageBox.information(self, "Success", "License applied!")
            self.accept()
            return

        # server
        ip = self._ip_edit.text().strip()
        port = self._port_edit.text().strip()
        if not ip or not port:
            QtWidgets.QMessageBox.warning(self, "Oops", "Enter both IP and Port.")
            return
        cmds.muLicenseCmd(activationType="server", serverIp=ip, serverPort=port)
        # Persist server values
        sets.setValue(self.SETTINGS_IP, ip)
        sets.setValue(self.SETTINGS_PORT, port)
        sets.sync()
        QtWidgets.QMessageBox.information(self, "Success", "Server set!")
        self.accept()


__all__ = ["LicenseDialog"]