import ScreenCloud
import time
from PythonQt.QtCore import QFile, QSettings
from PythonQt.QtGui import QDesktopServices, QMessageBox
from PythonQt.QtUiTools import QUiLoader
from multiprocessing import Pool,Process

from seafapi import *
from processors import DummyProcessor, DefaultProcessor, EncryptedProcessor
###############################
## This is a temporary fix, should be removed when a newer python version is used ##
import logging
logging.captureWarnings(True)
###############################

class SeafileUploader():
    def __init__(self):
        self.processor = DummyProcessor()
        self.seaf_lib = None
        self.seaf_path = "/"
        self.libs = None
        self.uil = QUiLoader()
        self.loadSettings()
        self.pool = Pool(2)
        
    def showSettingsUI(self, parentWidget):
        self.parentWidget = parentWidget
        self.settingsDialog = self.uil.load(QFile(workingDir + "/settings.ui"), parentWidget)
        self.settingsDialog.group_account.widget_loggedIn.loginButton.connect("clicked()", self.startAuthenticationProcess)
        #self.settingsDialog.group_name.input_name.connect("textChanged(QString)", self.nameFormatEdited)
        self.settingsDialog.group_location.widget_location.pathEdit.connect("textChanged(QString)", self.locationUpdate)
        self.settingsDialog.group_location.widget_location.libraryEditDrop.connect("currentIndexChanged(QString)", self.locationUpdate)
        self.settingsDialog.connect("accepted()", self.saveSettings)
        
        self.loadSettings()
        self.updateUi()
        self.settingsDialog.open()

    def populateLibrarySelector(self):
        drop = self.settingsDialog.group_location.widget_location.libraryEditDrop
        drop.clear()
        drop.setEnabled(False)
        select = 0
        if self.seaf_client:
            self.libs = (self.seaf_client or self.seaf_lib.client).libraries()
            i=0
            for lib in self.libs:
                if self.seaf_lib is not None and lib.id == self.seaf_lib.id:
                    select = i
                    print "set %s" % lib.name
                drop.addItem(lib.name)
                i=i+1
        drop.setCurrentIndex(select)
        drop.setEnabled(True)

    def updateUi(self):
        self.settingsDialog.group_account.widget_loggedIn.usernameEdit.setText(self.access_token.username if not (self.access_token is None)  else "")
        self.settingsDialog.group_account.widget_loggedIn.serverUrlEdit.setText(self.seaf_url or "https://seaf.shimun.net")
        self.settingsDialog.group_account.widget_loggedIn.loginButton.setText("Logout" if self.access_token is not None else "Login")
        #
        if self.access_token is None and len(self.settingsDialog.group_account.widget_loggedIn.passwordEdit.text) > 0:
            self.settingsDialog.group_account.widget_loggedIn.passwordEdit.setText("X" * 8)
        for elm in [self.settingsDialog.group_account.widget_loggedIn.usernameEdit, self.settingsDialog.group_account.widget_loggedIn.serverUrlEdit, self.settingsDialog.group_account.widget_loggedIn.passwordEdit]:
            elm.setEnabled(self.access_token is None)
        self.settingsDialog.group_location.setEnabled(self.access_token is not None)
        self.settingsDialog.group_location.widget_location.pathEdit.setText(self.lib_path or "/")
        self.settingsDialog.linkCopyCheck.setChecked(self.copyLink)
        self.populateLibrarySelector()
        self.settingsDialog.adjustSize()

    def loadSettings(self):
        settings = QSettings()
        settings.beginGroup("uploaders")
        settings.beginGroup("seafile")
        self.seaf_url = settings.value("seafile-url", "")
        (self.lib_id,self.lib_name) = str(settings.value("library", "/")).split("/")
        self.lib_path = settings.value("library-path", "")
        self.copyLink = settings.value("copy-link", "true") in ['true', True]
        if settings.value("auth-token", False) and settings.value("auth-username", False):
            self.access_token = SeafileToken(settings.value("auth-username", False),settings.value("auth-token", False))
        else:
            self.access_token = None
        self.nameFormat = settings.value("name-format", "Screenshot %Y-%m-%d %H_%M_%S")
        self.upload_scheme = settings.value("upload-scheme", "regular")
        settings.endGroup()
        settings.endGroup()
        if self.seaf_url and self.access_token:
            self.seaf_client = SeafileClient(self.seaf_url,self.access_token.username,token=self.access_token)
            for lib in self.seaf_client.libraries():
                if lib.id == self.lib_id:
                    self.seaf_lib = lib
            if self.seaf_lib and self.seaf_path:
                self.processor = EncryptedProcessor(self.seaf_lib,self.lib_path)#DefaultProcessor(self.seaf_lib,self.lib_path)
            

    def saveSettings(self):
        settings = QSettings()
        settings.beginGroup("uploaders")
        settings.beginGroup("seafile")
        try:
            self.copyLink = self.settingsDialog.linkCopyCheck.checked
        except:
            pass
        settings.setValue("copy-link", self.copyLink)
        if self.access_token is not None:
            settings.setValue("auth-username", self.access_token.username )
            settings.setValue("auth-token", self.access_token.token)
        settings.setValue("seafile-url", self.seaf_url)
        if self.seaf_lib is not None:
            settings.setValue("library", "%s/%s" % (self.seaf_lib.id,self.seaf_lib.name))
        settings.setValue("library-path", self.lib_path)
        settings.setValue("name-format", self.nameFormat)
        settings.setValue("upload-scheme", self.upload_scheme)
        #settings.setValue("name-format", self.settingsDialog.group_name.input_name.text)
        print self.seaf_lib, self.lib_path
        settings.endGroup()
        settings.endGroup()
    
    def isConfigured(self):
        return self.access_token and self.seaf_url and self.processor.is_configured()

    def getFilename(self):
        self.loadSettings()
        return ScreenCloud.formatFilename(self.nameFormat)
          
    def upload(self, screenshot, name):
        self.loadSettings()
        #Make sure we have a up to date token
        if not self.seaf_lib:
            ScreenCloud.setError("Not configured properly")
            return False
            #Save to a temporary file
        timestamp = time.time()
        def tempfile(name):
            try:
                return QDesktopServices.storageLocation(QDesktopServices.TempLocation) + "/" + name
            except AttributeError:
                from PythonQt.QtCore import QStandardPaths #fix for Qt5
                return QStandardPaths.writableLocation(QStandardPaths.TempLocation) + "/" + name

        tmpFilename = tempfile(ScreenCloud.formatFilename(str(timestamp)))
        screenshot.save(QFile(tmpFilename), ScreenCloud.getScreenshotFormat())
                #Upload!
        link=None
        if True:
        #try:
            link = self.processor.upload(tmpFilename,self.getFilename())
            if self.copyLink:
                ScreenCloud.setUrl(link)
        #except Exception as e:
           # ScreenCloud.setError("Failed to upload to seafile. " + e.message)
           # return False
        return True

    def startAuthenticationProcess(self):
        self.saveSettings()
        self.loadSettings()

        if self.access_token is not None:
            self.logOut()
            return

        if self.settingsDialog.group_account.widget_loggedIn.serverUrlEdit.text \
                and self.settingsDialog.group_account.widget_loggedIn.usernameEdit.text \
                and self.settingsDialog.group_account.widget_loggedIn.passwordEdit.text:
            self.seaf_url = self.settingsDialog.group_account.widget_loggedIn.serverUrlEdit.text
            if True:
            #try:
                self.login(self.settingsDialog.group_account.widget_loggedIn.usernameEdit.text,self.settingsDialog.group_account.widget_loggedIn.passwordEdit.text)
                self.saveSettings()
                self.loadSettings()
                self.populateLibrarySelector()
            #except Exception as e:
                #QMessageBox.critical(self.settingsDialog, "Failed to login", "Verify your server url and credentials" + e.message)
        self.saveSettings()
        self.updateUi()

    def locationUpdate(self):
        drop = self.settingsDialog.group_location.widget_location.libraryEditDrop
        selected_lib = drop.currentText
        if not drop.isEnabled(): return #not populated
        self.lib_path = self.settingsDialog.group_location.widget_location.pathEdit.text
        print self.lib_path, selected_lib
        if self.libs is None: return
        for lib in self.libs:
            if lib.name == selected_lib:
                self.seaf_lib = lib
                print "%s user selected" % selected_lib


    def login(self,user,password):
        cli = SeafileClient(self.seaf_url,user,password)
        self.access_token = cli.obtain_token()

    def logOut(self):
        settings = QSettings()
        settings.beginGroup("uploaders")
        settings.beginGroup("seafile")
        settings.remove("auth-token")
        self.access_token = None
        settings.endGroup()
        settings.endGroup()
        self.loadSettings()
        self.updateUi()

    def nameFormatEdited(self, nameFormat):
        self.settingsDialog.group_name.label_example.setText(ScreenCloud.formatFilename(nameFormat, False))

