import c4d
from ssp_ids import *
from ssp_utils_pref import *
from ssp_utils import *
from ssp_dialog_ssp import DialogMain
from ssp_dialog_auth import Auth, TestAuth


g_dlgMain = None

# To be called during shutdown
def CmdSSPDestroyGlobals():
    global g_dlgMain

    if g_dlgMain is not None:
        if not g_dlgMain.Close():
            c4d.gui.MessageDialog('{0} SEVERE ISSUE: FAILED TO CLOSE DIALOG'.format(PLUGIN_NAME))

        g_dlgMain = None


####################################################################################################
# Class CommandDataSSP #############################################################################
####################################################################################################
class CommandDataSSP(c4d.plugins.CommandData):
    _dlgMain = None


    def Execute(self, doc):
        if not Auth():
            return True

        global g_dlgMain

        bcInputState = c4d.BaseContainer()
        if c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD, c4d.BFM_INPUT, bcInputState):
            if bcInputState[c4d.BFM_INPUT_QUALIFIER] & 0x02: # TODO Andreas: c4d.QUALIFIER_CTRL??? c4d.QCTRL???
                bcScenesNames = GetScenesNames()
                bcMenu = c4d.BaseContainer()
                for idxDoc, (idDoc, nameDoc) in enumerate(bcScenesNames):
                    sShortcut = ''

                    if GetPrefShowShortcuts():
                        sShortcut = SwitchShortcutToString(idxDoc)

                    bcMenu.InsData(idDoc, nameDoc + sShortcut)

                idDoc = c4d.gui.ShowPopupDialog(cd=None, bc=bcMenu, x=c4d.MOUSEPOS, y=c4d.MOUSEPOS)
                if idDoc == 0:
                    return True

                doc = c4d.documents.GetFirstDocument()
                while doc is not None:
                    _, idDocTest, _, _ = GetDocumentPathFull(doc)

                    if idDocTest == idDoc:
                        break

                    doc = doc.GetNext()

                if doc is not None:
                    c4d.documents.SetActiveDocument(doc)
                    c4d.EventAdd()

                return True

        if self._dlgMain is None:
            self._dlgMain = DialogMain()
            g_dlgMain = self._dlgMain

        if self._dlgMain is None:
            print('{0} ERROR: Unable to allocate main dialog.'.format(PLUGIN_NAME))
            return True

        if c4d.GetC4DVersion() // 1000 >= 25:
            if self._dlgMain.IsOpen() and not self._dlgMain.GetFolding():
                self._dlgMain.SetFolding(True)
                return True

        else:
            if self._dlgMain.IsOpen():
                self._dlgMain.Close()
                return True

        self._dlgMain.Open(c4d.DLG_TYPE_ASYNC, PLUGIN_ID, xpos=-1, ypos=-1, defaultw=500, defaulth=0) # pos: -1: mouse pos, -2: screen center

        return True


    def ExecuteOptionID(self, doc, plugid, subid):
        if not Auth():
            return True

        # Workaround for "Options being called from Extensions menu"
        # https://plugincafe.maxon.net/topic/12894/different-behavior-on-mac-for-commanddata-options
        # https://plugincafe.maxon.net/topic/11837/r21-commanddata-with-option-not-working-on-macos
        if c4d.GeGetCurrentOS() == c4d.OPERATINGSYSTEM_OSX and c4d.GetC4DVersion() // 1000 >= 21:
            if subid == 0:
                c4d.CallCommand(PLUGIN_ID)
                return True

        if c4d.GetC4DVersion() // 1000 >= 19:
            c4d.PrefsLib_OpenDialog(PLUGIN_ID_PREFS)

        else:
            c4d.CallCommand(PLUGIN_ID_OPTIONS)

        return True


    def RestoreLayout(self, secref):
        if not TestAuth():
            return True

        if self._dlgMain is None:
            global g_dlgMain

            self._dlgMain = DialogMain()
            g_dlgMain = self._dlgMain

        return self._dlgMain.Restore(PLUGIN_ID, secref)


    def GetState(self, doc):
        if not GetPrefPluginEnabled():
            return 0

        state = c4d.CMD_ENABLED

        if self._dlgMain is None:
            return state

        isFolded = False
        if c4d.GetC4DVersion() // 1000 >= 25:
            isFolded = self._dlgMain.GetFolding()

        if self._dlgMain.IsOpen() and not isFolded:
            state |= c4d.CMD_VALUE

        return state
