import os
from PySide2 import QtCore, QtGui, QtWidgets
from installer.installercore import InstallerCore
from installer import utils
import maya.api.OpenMaya as om2

RELATIVE_IMAGE = "install_files/zoo_rhino.jpg"


# ----------------------------------------
# Main UI
# ----------------------------------------

class InstallDialog(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(InstallDialog, self).__init__(parent)

        self.setProperty("saveWindowPref", True)
        self.parent = parent

        self.setWindowTitle("Zoo Tools Pro Installer")
        self.setMinimumWidth(600)
        self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        self.core = InstallerCore()

        self._createWidgets()
        self.refreshInstallUpdateBtns()  # update the install or refresh button

        self.createLayouts()
        self.connections()


    def createImage(self, parent):
        """Creates the image from the RELATIVE_IMAGE path"""
        zooImagePath = os.path.join(self.currentDirectory(), RELATIVE_IMAGE)
        zooImage = QtWidgets.QLabel(parent)
        zooImage.setGeometry(0, 0, 580, 453)
        zooImage.setPixmap(QtGui.QPixmap(zooImagePath))
        return zooImage

    @classmethod
    def currentDirectory(cls):
        return os.path.dirname(os.path.realpath(__file__))

    def _createWidgets(self):
        """ Create widgets

        :return:
        """
        self.zooImage = self.createImage(None)

        self.scriptsLabel = QtWidgets.QLabel("Scripts Path")

        installed = self.core.installedZooPath()
        scriptsPath = self.core.scriptsDirectory
        if installed:
            scriptsPath = os.path.dirname(installed)
        self.scriptsPathTxt = QtWidgets.QLineEdit(scriptsPath)
        self.scriptsBrowseBtn = QtWidgets.QPushButton(parent=self, text="...")
        self.scriptsBrowseBtn.setMinimumWidth(30)

        self.moduleLabel = QtWidgets.QLabel("Module Path")

        modPath = self.core.moduleDirectory
        if installed:
            modPath = self.core.installedModPath() or modPath
        self.modulePathTxt = QtWidgets.QLineEdit(modPath)
        self.moduleBrowseBtn = QtWidgets.QPushButton(parent=self, text="...")
        self.moduleBrowseBtn.setMinimumWidth(30)

        self.prefLabel = QtWidgets.QLabel("Zoo Prefs Path")
        prefPath = self.core.zooPrefsDirectory
        if installed:
            prefPath = self.core.userPreferencePath(installed)

        self.prefPathTxt = QtWidgets.QLineEdit(prefPath)
        self.prefBrowseBtn = QtWidgets.QPushButton(parent=self, text="...")
        self.prefBrowseBtn.setMinimumWidth(30)

        self.installButton = QtWidgets.QPushButton(parent=self, text="Install Zoo Tools Pro")
        upgradeText = "Upgrade/Replace Zoo Tools Pro"
        if self.core.isNewerVersion() == "NO":
            upgradeText = "DOWNGRADE to Zoo Tools Pro version '{}'".format(self.core.versionPretty())
        self.upgradeButton = QtWidgets.QPushButton(parent=self, text=upgradeText)
        self.helpButton = QtWidgets.QPushButton(parent=self, text="Help")

    def createLayouts(self):
        """ Create layouts

        :return:
        """
        mainLayout = QtWidgets.QVBoxLayout(self)

        scriptsLayout = QtWidgets.QHBoxLayout(self)
        scriptsLayout.addWidget(self.scriptsLabel, 6)
        scriptsLayout.addWidget(self.scriptsPathTxt, 30)
        scriptsLayout.addWidget(self.scriptsBrowseBtn, 1)

        moduleLayout = QtWidgets.QHBoxLayout(self)
        moduleLayout.addWidget(self.moduleLabel, 6)
        moduleLayout.addWidget(self.modulePathTxt, 30)
        moduleLayout.addWidget(self.moduleBrowseBtn, 1)

        prefLayout = QtWidgets.QHBoxLayout(self)
        prefLayout.addWidget(self.prefLabel, 6)
        prefLayout.addWidget(self.prefPathTxt, 30)
        prefLayout.addWidget(self.prefBrowseBtn, 1)

        buttonLayout = QtWidgets.QHBoxLayout(self)
        buttonLayout.addWidget(self.installButton, 5)
        buttonLayout.addWidget(self.upgradeButton, 5)
        buttonLayout.addWidget(self.helpButton, 1)

        mainLayout.addWidget(self.zooImage)
        mainLayout.addLayout(scriptsLayout)
        mainLayout.addLayout(moduleLayout)
        mainLayout.addLayout(prefLayout)
        mainLayout.addLayout(buttonLayout)

    def refreshInstallUpdateBtns(self):
        """ Refresh Install update buttons

        :return:
        """
        if self.core.isZooInstalled():
            self.installButton.setVisible(False)
            self.upgradeButton.setVisible(True)
        else:
            self.installButton.setVisible(True)
            self.upgradeButton.setVisible(False)

    def browseScriptsPath(self):
        """ Browse scripts path button pressed

        :return:
        """

        directoryPath = QtWidgets.QFileDialog.getExistingDirectory(self,
                                                                   "Set Scripts Directory",
                                                                   self.scriptsPathTxt.text())
        self.sender().setDown(False)  # unstuck the button
        if not directoryPath:
            return
        self.core.scriptsDirectory = directoryPath
        self.refreshInstallUpdateBtns()  # update the install or refresh button
        self.scriptsPathTxt.setText(directoryPath)

    def browseModulesPath(self):
        """ Browse Modules path

        :return:
        """
        directoryPath = QtWidgets.QFileDialog.getExistingDirectory(self,
                                                                   "Set Modules Directory",
                                                                   self.modulePathTxt.text())
        self.sender().setDown(False)  # unstuck the button
        if not directoryPath:
            return
        self.core.moduleDirectory = directoryPath
        self.modulePathTxt.setText(directoryPath)

    def browsePrefsPath(self):
        """ Browse Modules path

        :return:
        """
        path = os.path.expanduser("~/zoo_preferences")
        directoryPath = QtWidgets.QFileDialog.getExistingDirectory(self,
                                                                   "Set Preferences Directory",
                                                                   path)
        self.sender().setDown(False)  # unstuck the button
        if not directoryPath:
            return
        self.core.moduleDirectory = directoryPath
        self.prefPathTxt.setText(directoryPath)

    def openHelp(self):
        """ Open help link

        :return:
        """
        import webbrowser
        webbrowser.open('https://create3dcharacters.com/maya-zoo-tools-pro-installer')

    def installUpgrade(self):
        """ Install and upgrade button pressed

        :return:
        """

        if self.core.isNewerVersion() == "NO":
            installed = self.core.installedVersionPretty()
            version = self.core.versionPretty()
            message = "You are about to downgrade ZooTools Pro from:\n\n'{}' to '{}'\n\nAre you sure you want to do this?".format(
                installed, version)
            res = utils.MessageBoxQt.showQuestion(self, "DOWNGRADE '{}'?".format(version),
                                                  message=message, buttonA="Yes", buttonB="Cancel")
            if res == "B":
                om2.MGlobal.displayWarning("Installation Cancelled")
                return

        scripts = self.scriptsPathTxt.text()
        modPath = self.modulePathTxt.text()
        prefPath = self.prefPathTxt.text()
        self.sender().setDown(False)  # unstuck the button
        self.refreshInstallUpdateBtns()  # update the install or refresh button
        self.core.install(scripts, modPath, prefPath)
        self.close()
        # ping custom zoo install number

    def connections(self):
        """ Connections

        :return:
        """
        self.scriptsBrowseBtn.pressed.connect(self.browseScriptsPath)
        self.moduleBrowseBtn.pressed.connect(self.browseModulesPath)
        self.prefBrowseBtn.pressed.connect(self.browsePrefsPath)
        self.helpButton.pressed.connect(self.openHelp)
        self.installButton.pressed.connect(self.installUpgrade)
        self.upgradeButton.pressed.connect(self.installUpgrade)

    def closeEvent(self, event):
        self.close()


# ----------------------------------------
# RUN DRAG AND DROP
# ----------------------------------------

def onMayaDroppedPythonFile(*args, **kwargs):
    """Main function that runs while dragging the file into Maya.

    Will install Zoo Tools Pro so long as the install folders are located beside this python file.
    """
    install = InstallDialog(utils.mayaMainWindow())
    install.show()
