#!/usr/bin/env python
#-*- coding: UTF-8 -*-

__author__ = "helljump"


APPNAME = 'cm3'


from PyQt4 import QtCore
from PyQt4 import QtGui
from ui import icons_rc  # @UnusedImport
import sys


class Translator(QtCore.QTranslator):

    def __init__(self, parent, lang):
        QtCore.QTranslator.__init__(self, parent)
        self.load(lang)

    def translate(self, context, sourceText, hmm=None):
        res = QtCore.QTranslator.translate(self, context, sourceText)
        if len(res) == 0:
            res = QtCore.QString(unicode(sourceText, "utf-8"))
        return res

app = QtGui.QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon(':/aaaa32.png'))
tr = Translator(None, 'qt_%s.qm' % QtCore.QLocale.system().name())
app.installTranslator(tr)


class MySplash(QtGui.QSplashScreen):
    def __init__(self):
        pm = QtGui.QPixmap(":/aaaa.png")
        super(MySplash, self).__init__(pm)

    def message(self, s):
        self.showMessage(s, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignTop, QtCore.Qt.white)
        QtGui.qApp.processEvents()


SPLASH = MySplash()
SPLASH.show()
SPLASH.message(u'Инициализация')


import logging.handlers
import os
import atexit
from ZODB.FileStorage import FileStorage
from ZODB.DB import DB as ZDB
from persistent.dict import PersistentDict
import transaction


from Crypto.Hash import SHA
import win32api
import marshal
from Crypto.Cipher import Blowfish
import types
hash_ = SHA.new()
d, p = os.path.splitdrive(win32api.GetSystemDirectory())
hash_.update(str(win32api.GetSystemInfo()))
hash_.update(APPNAME)
hash_.update(str(win32api.GetVolumeInformation(d + '/')))
HWINFO = hash_.hexdigest()
cipher = Blowfish.new(HWINFO)


egg = os.path.expanduser('~/' + APPNAME)
HOMEDIR = unicode(egg, encoding=sys.getfilesystemencoding())
if not os.path.isdir(HOMEDIR):
    os.mkdir(HOMEDIR)
DUMPDIR = HOMEDIR + '/dump'
if not os.path.isdir(DUMPDIR):
    os.mkdir(DUMPDIR)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(module)s: %(message)s")
logname = os.path.expanduser(os.path.join(HOMEDIR, APPNAME + '.log'))
handler1 = logging.handlers.RotatingFileHandler(logname, maxBytes=100000, backupCount=2)
handler1.setFormatter(formatter)
logger.addHandler(handler1)
if not hasattr(sys, "frozen"):
    handler2 = logging.StreamHandler(sys.stdout)
    handler2.setFormatter(formatter)
    logger.addHandler(handler2)
log = logging.getLogger(__name__)


olds = [
    '8c05dd496491b4c0f2d5b615fc0dfb97b5345f34'
]


CFG = QtCore.QSettings('zipta.ru', APPNAME)


SPLASH.message(u'Оптимизируем базу')
storage = FileStorage(os.path.join(HOMEDIR, 'db'))  # , blob_dir=os.path.join(HOMEDIR, 'blobs'))
DB = ZDB(storage)
CONN = DB.open()


root = CONN.root()
if "prefs" not in root:
    root["prefs"] = PersistentDict()
    transaction.commit()


def zodbclose():
    CONN.close()
    DB.pack(days=0)
    DB.close()
    storage.close()
    log.debug('base closed')
atexit.register(zodbclose)



# пример замены метода
#try:
#    u = __import__('userdata')
#    model.add_item = types.MethodType(u.add_item, model)
#except ImportError:
#    pass

''' demo
try:
    if HWINFO in olds:
        raise Exception()
    finp = os.path.join(HOMEDIR, 'userdata.pye')
    if os.path.isfile(finp):
        enc = open(finp, 'rb').read()
        data = cipher.decrypt(enc)
        m = types.ModuleType('userdata')
        sys.modules['userdata'] = m
        code = marshal.loads(data)
        exec code in m.__dict__
except:
    log.debug('ohh')
'''

SPLASH.message(u'Запуск интерфейса')

try:
    m = __import__('BUILD_CONSTANTS')
    log.debug('Version: %s', m.BUILD_TIMESTAMP)
except ImportError, err:
    log.debug('Dev mode')
