'''
Described at PyMOL wiki: http://www.pymolwiki.org/index.php/lisica
 
'''
from __future__ import absolute_import
from __future__ import print_function
import os
import stat
import urllib.request, urllib.error, urllib.parse
from urllib.request import urlopen
from urllib.error import URLError, HTTPError
import zipfile
import tempfile
import shutil
import sys
import platform
from distutils.dir_util import copy_tree
import time
from threading import Thread
import contextlib
# entry point to PyMOL's API
from pymol import cmd
# pymol.Qt provides the PyQt5 interface, but may support PyQt4
# and/or PySide as well
from pymol.Qt import QtWidgets
from pymol.Qt.utils import loadUi

HOME_DIRECTORY=os.path.expanduser('~')
LISICA_DIRECTORY=os.path.join(HOME_DIRECTORY,".lisicagui")
UI_DIRECTORY=os.path.join(LISICA_DIRECTORY,"UI")
versionFile = os.path.join(LISICA_DIRECTORY, "version.txt")

def __init_plugin__(app=None):
    '''
    Add an entry to the PyMOL "Plugin" menu
    '''
    from pymol.plugins import addmenuitemqt
    addmenuitemqt("LiSiCA - Ligand Similarity using Clique Algorithm", lambda: run())

dialog = None
class Configuration:
    def __init__(self):

        self.system = platform.system()
        self.machine = platform.machine()
        self.architecture = platform.architecture()
        import struct
        self.python_bit = 8 * struct.calcsize("P")
        self.python_version = platform.python_version_tuple()

    def is_os_64bit(self):
        if self.system == 'Windows':
            return platform.architecture()[0] == "64bit"
        else:
            return platform.machine().endswith('64')

    def exe_File(self):
        if self.system == 'Windows':
            if self.is_os_64bit():
                exe_filename = "LiSiCAx64.exe"
            else:
                exe_filename = "LiSiCAx86.exe"

        elif self.system == 'Linux':
            exe_filename = "lisica"
        else:
            print ("The plugin might not be compatible with your machine")
            exe_filename = "lisica"
        return exe_filename
        
    
    
class UpdateCheck:

    def __init__(self):
        self.firstVersionURL = "http://insilab.org/files/lisica-plugin/version.txt"
        self.firstArchiveURL = "http://insilab.org/files/lisica-plugin/archive.zip"
        self.currentVersion=""
        self.latestVersion =""


    def installationFailed(self):
        global running, status
        status = "failed"
        running = False

    def deleteTmpDir(self):
        try:
            shutil.rmtree(self.tmpDir)
            print(("deleted temporary ", self.tmpDir))
        except:
            print ("error : could not remove temporary directory")


    def createTmpDir(self):
        try:
            self.tmpDir= tempfile.mkdtemp()
            print(("created temporary ", self.tmpDir))
        except:
            print ("error : could not create temporary directory")
            self.installationFailed()
        self.zipFileName=os.path.join(self.tmpDir, "archive.zip")

    def downloadInstall(self):
        try:
            print ("Fetching plugin from the Insilab server at http://insilab.org")
            urlcontent = urlopen(self.firstArchiveURL, timeout=5)
            zipcontent = urlcontent.read()
            LiSiCAzipFile = open(self.zipFileName, 'wb')
            LiSiCAzipFile.write(zipcontent)
        except HTTPError as e1:
            print(("HTTP Error:", e1.code, e1.reason))
            self.installationFailed()
        except URLError as e2:
            print(("URL Error:", e2.reason))
            self.installationFailed()
        except Exception as e:
            print ("Error: download failed, check if http://insilab.org website is up...")
            self.installationFailed()
        finally:
            try:
                LiSiCAzipFile.close()
            except:
                pass
            try:
                urlcontent.close()
            except:
                pass

    def extractInstall(self):
        # this must be called before import LisicaGUI, otherwise
        # rmtree will fail on NFS systems due to open log file handle
        try:
            with contextlib.closing(zipfile.ZipFile(self.zipFileName, "r")) as LiSiCAzip:
                for member in LiSiCAzip.namelist():
                    masterDir = os.path.dirname(member)
                    break
                LiSiCAzip.extractall(self.tmpDir)
            # copy new
            copy_tree(os.path.join(self.tmpDir, masterDir, ".lisicagui"), LISICA_DIRECTORY)
        except:
            print ("installation of lisicagui failed")
            self.installationFailed()

    def firstUpgrade(self):
        return not os.path.isdir(LISICA_DIRECTORY)


    def upgrade(self):
        
        self.createTmpDir()
        self.downloadInstall()
        self.extractInstall()
        self.deleteTmpDir()

        # add executable properties
        configure=Configuration()
        exe_filename=configure.exe_File()
        exe_path=os.path.normpath(os.path.join(LISICA_DIRECTORY,"bin",exe_filename))
        st = os.stat(exe_path)
        os.chmod(exe_path, st.st_mode | stat.S_IEXEC)

        sys.path.append(os.path.normpath(os.path.join(LISICA_DIRECTORY, "modules")))
        #self.findLatestVersion()
        #self.writeToVersionTxt(self.latestVersion)

        print ("Upgrade finished successfully!")
        global running, status
        status = "start"
        running = False
        #start_lisica()
        #main()

    def findCurrentVersion(self):
        if os.path.isfile(versionFile):
            with open(versionFile, 'r') as myFile:
                global currentVersion
                lines = myFile.readlines()
                if len(lines) == 1:
                    self.currentVersion = lines[0].strip()
                else:
                    date = lines[len(lines)-1].split('\t')[2]
                    t = time.strftime("%d/%m/%Y")

                    tmpTime1 = date.split('/')
                    tmpTime2 = t.split('/')
                    if int(tmpTime2[2]) > int(tmpTime1[2]) or int(tmpTime2[1]) > int(tmpTime1[1]) or int(tmpTime2[0]) > int(tmpTime1[0])+15:
                        self.currentVersion = lines[0].strip()
                    else:
                        self.currentVersion = (lines[len(lines)-1].split('\t')[0]).strip()
                currentVersion = self.currentVersion
                #print(str(self.currentVersion))

    def findLatestVersion(self):
        try:
            global latestVersion
            # from insilab git server
            versionFile = urllib.request.urlopen(self.firstVersionURL, timeout=5)
            self.latestVersion = versionFile.read().decode(encoding="utf-8").strip()
            if len(self.latestVersion) > 6:
                self.latestVersion = ""
            latestVersion = self.latestVersion
            #print(str(self.latestVersion))
            
        except HTTPError as e1:
            print(("HTTP Error:", e1.code, e1.reason))
        except URLError as e2:
            print(("URL Error:", e2.reason))
        except Exception as e:
            print ("URL Error: Is Insilab webpage (http://insilab.org) down?")

    #
    # write to version.txt file
    #
    def writeToVersionTxt(version, reminder=False):
        if reminder:
            with open(versionFile, 'a') as myfile:
                myfile.write(str(version)+"\t later \t"+time.strftime("%d/%m/%Y")+"\n")
        else:
            with open(versionFile, 'w') as myfile:
                myfile.write(str(version)+"\n".encode("ascii"))
    #
    # yes or no update window
    #
    def updateBox(self):
        global updateDialog

        #if updateDialog is None:
        updateDialog = self.updateWindow()

        updateDialog.show()
    
    def updateWindow(self):
        global updateDialog
        #print("Started update box")
    # create a new Window
        updateDialog = QtWidgets.QMainWindow()

    # populate the Window from our *.ui file which was created with the Qt Designer
        uifile = os.path.join(UI_DIRECTORY, 'GUIupdate.ui')
        form = loadUi(uifile, updateDialog)

        def cancelButton():
            global status
            if form.checkBoxAsk.isChecked():
                self.writeToVersionTxt(self.latestVersion, True)
            #status = "start"
            updateDialog.close()
            start_lisica()
            

        def updateButton(vent=None):
            global status
            #status = "update"
            #run_dialog("Lisica Updating...")
            updateDialog.close()
            self.upgrade()
            start_lisica()
            
        self.findLatestVersion()
        self.findCurrentVersion()
    
    # hook up button callbacks
        form.labelVersionLatest.setText(str(self.latestVersion))
        form.labelVersionCurrent.setText(str(self.currentVersion))
        form.buttonBoxUpdate.accepted.connect(lambda: updateButton())
        form.buttonBoxUpdate.rejected.connect(lambda: cancelButton())
    
        return updateDialog


def internetOn():
        try:
            urllib.request.urlopen('http://insilab.org',timeout=5)
            return True
        except:
            return False

def msgButtonClick(i):
   print("Button clicked is:",i.text())
   
def showManualDlInfo():
    msgBox = QtWidgets.QMessageBox()
    msgBox.setIcon(QtWidgets.QMessageBox.Information)
    msgBox.setText("Installation failed: To download and manually install LiSiCA GUI please visit our website http://www.insilab.org/lisica/download.php .")
    msgBox.setWindowTitle("Instalation error message")
    msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
    msgBox.buttonClicked.connect(msgButtonClick)   

class FuncThread(Thread):
    def __init__(self, target, *args):
        Thread.__init__(self)
        self._target = target
        self._args = args

    def run(self, *args):
        self._target(*self._args)

def run_dialog(process):
    '''
    Open our custom dialog
    '''
    global dialog

    #if dialog is None:
    dialog = make_dialog(process)

    dialog.show()

def make_dialog(proc):
    global dialog
    # create a new Window
    dialog = QtWidgets.QDialog()
    
     #populate the Window from our *.ui file which was created with the Qt Designer
    uifile = os.path.join(UI_DIRECTORY, 'LisicaStarting.ui')
    form = loadUi(uifile, dialog)
    
    #print("Started dialog: %s" % proc)
    form.labelStarting.setText("%s" % proc)
    return dialog

def start_lisica():
    print(("Python version: "+platform.architecture()[0]))
    sys.path.append(os.path.normpath(os.path.join(LISICA_DIRECTORY, "modules")))
    #del status # remove global variables
    import LisicaGUI
    LisicaGUI.main()

def run():

    print("Initialising LiSiCA ...")

    global running, status
    status = "start"

    try:
        sys.path.remove('')
    except:
        pass

    if UpdateCheck().firstUpgrade():
        print("First time installation...")
        if not internetOn():
            status = "no-internet"
        else:
            UpdateCheck().findLatestVersion()
            UpdateCheck().upgrade()
    else:
        UpdateCheck().findCurrentVersion()
        print("Not First time installation")
        if internetOn() == True:
            UpdateCheck().findLatestVersion()
            #print("internet on")
            if str(latestVersion) != str(currentVersion):
                print("Update Needed!")
                status = "check-update"
    
    running = False
    main()

def main():
    global status
    run_dialog("Starting Lisica software...")
    if status == "no-internet":
        msgBox = QtWidgets.QMessageBox()
        msgBox.setIcon(QtWidgets.QMessageBox.Information)
        msgBox.setText("Communication Error: No Internet connection available. Please make sure that your device is connected to the Internet.")
        msgBox.setWindowTitle("Communication error message")
        msgBox.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel)
        msgBox.buttonClicked.connect(msgButtonClick)   

    if status == "check-update":
        dialog.close()
        UpdateCheck().updateBox()

    if status == "start":
        dialog.close()
        start_lisica()

    else:
        showManualDlInfo()

