import time

from encryptedscreenshot import EncryptedScreenshot, Signer
import getpass, os
from PythonQt.QtGui import QInputDialog
from PythonQt.QtCore import QSettings
from seafapi import *

class Processor:

    def configure(self,parent):
        pass

    def is_configured(self):
        return True

    def upload(self,file):
        pass

class DummyProcessor(Processor):

    def is_configured(self):
        return False

class DefaultProcessor(Processor):

    def __init__(self,seaf_lib,lib_path):
        self.seaf_lib = seaf_lib
        self.lib_path = lib_path

    def upload(self,file,name):
        return self.seaf_lib.upload(file,name,self.lib_path).share()

class EncryptedProcessor(Processor):

    def __init__(self,seaf_lib,lib_path):
        self.seaf_lib = seaf_lib
        self.lib_path = lib_path
        self.load_settings()
        self.host = ""

    def load_settings(self):
        settings = QSettings()
        settings.beginGroup("uploaders")
        settings.beginGroup("seafile")
        self.host = settings.value("encscreen-url", "")
        settings.endGroup()
        settings.endGroup()

    def save_settings(self):
        settings = QSettings()
        settings.beginGroup("uploaders")
        settings.beginGroup("seafile")
        settings.setValue("encscreen-url", self.host)
        settings.endGroup()
        settings.endGroup()

    def is_configured(self):
        return self.host is not None and self.host != ""

    def configure(self,parent):
        self.host = QInputDialog.getText(parent, 'Encscreen Server Setup', 'Enter server url (ex. https://servertld/s#%id%key):', text="https://screens.shimun.net/s#%id%key")
        self.save_settings()

    def upload(self,file,name):
        enrypted = EncryptedScreenshot({
            "owner": unicode(getpass.getuser()),
            "format": unicode(str(file).split('.')[-1]),
            "title": unicode(name),
            "timestamp": int(time.time() * 1000),
            "size": os.stat(file).st_size
        },signer=Signer.default())
        tmpHandle = open(file + "c", 'wb')
        tmpHandle.write(enrypted.assemble(file))
        tmpHandle.close()
        seaf_file = self.seaf_lib.upload(file + "c",name + ".enc",self.lib_path)
        if not seaf_file:
            return
        seaf_link = seaf_file.share()
        if seaf_link:
            id = str(seaf_link).split('/')[-2]
            return self.host.replace('%id', id).replace('%key',"%s" % enrypted.password)
        else:
            return False


