# Path: reggata/data/db_schema.py
# class Thumbnail(Base):
# 
#     __tablename__ = "thumbnails"
# 
#     data_ref_id = sqa.Column(sqa.Integer, ForeignKey("data_refs.id"), primary_key=True)
# 
#     # Size of thumbnail in pixels
#     size = sqa.Column(sqa.Integer, primary_key=True)
# 
#     data = sqa.Column(sqa.LargeBinary)
# 
#     date_created = sqa.Column(sqa.DateTime)
# 
#     def __init__(self):
#         self.data_ref_id = None
#         self.size = None
#         self.data = None
#         self.date_created = datetime.datetime.today()
# 
#     @staticmethod
#     def _sql_from():
#         return '''
#         thumbnails.data_ref_id AS thumbnails_data_ref_id,
#         thumbnails.size AS thumbnails_size,
#         thumbnails.data AS thumbnails_data,
#         thumbnails.date_created AS thumbnails_date_created '''
# 
# Path: reggata/data/integrity_fixer.py
# class IntegrityFixerFactory(object):
# 
#     @staticmethod
#     def createFixer(code, strategy, uow, repo_base_path, items_lock):
#         if code == Item.ERROR_FILE_NOT_FOUND:
#             return FileNotFoundFixer(strategy, uow, repo_base_path, items_lock)
# 
#         elif code == Item.ERROR_FILE_HASH_MISMATCH:
#             return FileHashMismatchFixer(strategy, uow, repo_base_path, items_lock)
# 
#         else:
#             assert False, "There is no fixer class for item integrity error code {0}.".format(code)
# 
# Path: reggata/helpers.py
# def is_none_or_empty(s):
#     '''
#         Returns True, if given string s is None or "" (empty string).
#     If s is and instance of class different from str, function raises TypeError.
#     '''
#     if s is None:
#         return True
#     else:
#         if not isinstance(s, str):
#             raise TypeError("is_none_or_empty() can be applied only to str objects.")
#         return True if s == "" else False
# 
# Path: reggata/memento.py
# class Serializable(object):
# class Encoder(json.JSONEncoder):
#     def toJson(self):
#     def fromJson(objState):
#     def __init__(self, indent=4, sort_keys=True):
#     def default(self, obj):
# def Decoder():
# def hook(objState):
# 
# Path: reggata/user_config.py
# class UserConfig(object):
#     '''
#         This class is an interface for reggata.conf configuration file.
#     It is a singleton class.
#     '''
#     _instance = None
#     _props = None
# 
#     def __new__(cls, *args, **kwargs):
#         if not cls._instance:
#             cls._instance = super(UserConfig, cls).__new__(cls, *args, **kwargs)
# 
#             cls._props = Properties()
#             if not os.path.exists(consts.USER_CONFIG_DIR):
#                 os.makedirs(consts.USER_CONFIG_DIR)
# 
#             if not os.path.exists(consts.USER_CONFIG_FILE):
#                 with codecs.open(consts.USER_CONFIG_FILE, "w", "utf-8") as f:
#                     f.write(reggata_default_conf.reggataDefaultConf)
# 
#             with codecs.open(consts.USER_CONFIG_FILE, "r", "utf-8") as f:
#                 cls._props.load(f)
# 
#         return cls._instance
# 
#     def __init__(self):
#         pass
# 
#     def __getitem__(self, key):
#         '''
#             This is an operation []. It returns a value of parameter with given key.
#         If there is no such key, an exception is raised.
#         '''
#         return self._props[key]
# 
#     def get(self, key, default=None):
#         '''
#             Returns value of parameter with given key. If there are no such key in
#         configuration, then a default value is returned.
#         '''
#         return self._props.get(key, default)
# 
#     def store(self, key, value):
#         self._props[key] = str(value)
#         with codecs.open(consts.USER_CONFIG_FILE, 'w', "utf-8") as f:
#             self._props.store(f)
# 
#     def storeAll(self, d):
#         if type(d) != dict:
#             raise TypeError("This is not a dict instance.")
#         for key in d.keys():
#             self._props[key] = str(d[key])
#         with codecs.open(consts.USER_CONFIG_FILE, 'w', "utf-8") as f:
#             self._props.store(f)
# 
#     def refresh(self):
#         with codecs.open(consts.USER_CONFIG_FILE, 'r', "utf-8") as f:
#             self._props.load(f)


from tarfile import TarFile
from _pyio import open
from PyQt4 import QtCore, QtGui
from reggata.data.db_schema import Thumbnail
from reggata.data.integrity_fixer import IntegrityFixerFactory
from reggata.helpers import is_none_or_empty
from reggata import memento
from reggata.user_config import UserConfig
import tarfile
import logging
import os
import traceback
import datetime
import reggata.data.commands as cmds
import reggata.errors as errors
import reggata.consts as consts
import shutil
        This thread is started every time after any query execution in Intems Table Tool.
    '''
    def __init__(self, parent, repo, items, lock, rebuild=False):
        super(ThumbnailBuilderThread, self).__init__(parent)
        self.repo = repo
        self.items = items
        self.lock = lock
        self.interrupt = False
        self.rebuild = rebuild

    def doWork(self):
        uow = self.repo.createUnitOfWork()
        try:
            thumbnail_size = int(UserConfig().get("thumbnail_size", consts.THUMBNAIL_DEFAULT_SIZE))

            for i in range(len(self.items)):
                item = self.items[i]

                if self.interrupt:
                    logger.info("ThumbnailBuilderThread interrupted!")
                    break

                if not item.data_ref or not item.data_ref.is_image():
                    continue


                if self.rebuild == False and len(item.data_ref.thumbnails) > 0:
                    continue
                elif self.rebuild:
                    #Delete ALL existing thumbnails linked with current item.data_ref from database

# Path: reggata/data/db_schema.py
# class Thumbnail(Base):
# 
#     __tablename__ = "thumbnails"
# 
#     data_ref_id = sqa.Column(sqa.Integer, ForeignKey("data_refs.id"), primary_key=True)
# 
#     # Size of thumbnail in pixels
#     size = sqa.Column(sqa.Integer, primary_key=True)
# 
#     data = sqa.Column(sqa.LargeBinary)
# 
#     date_created = sqa.Column(sqa.DateTime)
# 
#     def __init__(self):
#         self.data_ref_id = None
#         self.size = None
#         self.data = None
#         self.date_created = datetime.datetime.today()
# 
#     @staticmethod
#     def _sql_from():
#         return '''
#         thumbnails.data_ref_id AS thumbnails_data_ref_id,
#         thumbnails.size AS thumbnails_size,
#         thumbnails.data AS thumbnails_data,
#         thumbnails.date_created AS thumbnails_date_created '''
# 
# Path: reggata/data/integrity_fixer.py
# class IntegrityFixerFactory(object):
# 
#     @staticmethod
#     def createFixer(code, strategy, uow, repo_base_path, items_lock):
#         if code == Item.ERROR_FILE_NOT_FOUND:
#             return FileNotFoundFixer(strategy, uow, repo_base_path, items_lock)
# 
#         elif code == Item.ERROR_FILE_HASH_MISMATCH:
#             return FileHashMismatchFixer(strategy, uow, repo_base_path, items_lock)
# 
#         else:
#             assert False, "There is no fixer class for item integrity error code {0}.".format(code)
# 
# Path: reggata/helpers.py
# def is_none_or_empty(s):
#     '''
#         Returns True, if given string s is None or "" (empty string).
#     If s is and instance of class different from str, function raises TypeError.
#     '''
#     if s is None:
#         return True
#     else:
#         if not isinstance(s, str):
#             raise TypeError("is_none_or_empty() can be applied only to str objects.")
#         return True if s == "" else False
# 
# Path: reggata/memento.py
# class Serializable(object):
# class Encoder(json.JSONEncoder):
#     def toJson(self):
#     def fromJson(objState):
#     def __init__(self, indent=4, sort_keys=True):
#     def default(self, obj):
# def Decoder():
# def hook(objState):
# 
# Path: reggata/user_config.py
# class UserConfig(object):
#     '''
#         This class is an interface for reggata.conf configuration file.
#     It is a singleton class.
#     '''
#     _instance = None
#     _props = None
# 
#     def __new__(cls, *args, **kwargs):
#         if not cls._instance:
#             cls._instance = super(UserConfig, cls).__new__(cls, *args, **kwargs)
# 
#             cls._props = Properties()
#             if not os.path.exists(consts.USER_CONFIG_DIR):
#                 os.makedirs(consts.USER_CONFIG_DIR)
# 
#             if not os.path.exists(consts.USER_CONFIG_FILE):
#                 with codecs.open(consts.USER_CONFIG_FILE, "w", "utf-8") as f:
#                     f.write(reggata_default_conf.reggataDefaultConf)
# 
#             with codecs.open(consts.USER_CONFIG_FILE, "r", "utf-8") as f:
#                 cls._props.load(f)
# 
#         return cls._instance
# 
#     def __init__(self):
#         pass
# 
#     def __getitem__(self, key):
#         '''
#             This is an operation []. It returns a value of parameter with given key.
#         If there is no such key, an exception is raised.
#         '''
#         return self._props[key]
# 
#     def get(self, key, default=None):
#         '''
#             Returns value of parameter with given key. If there are no such key in
#         configuration, then a default value is returned.
#         '''
#         return self._props.get(key, default)
# 
#     def store(self, key, value):
#         self._props[key] = str(value)
#         with codecs.open(consts.USER_CONFIG_FILE, 'w', "utf-8") as f:
#             self._props.store(f)
# 
#     def storeAll(self, d):
#         if type(d) != dict:
#             raise TypeError("This is not a dict instance.")
#         for key in d.keys():
#             self._props[key] = str(d[key])
#         with codecs.open(consts.USER_CONFIG_FILE, 'w', "utf-8") as f:
#             self._props.store(f)
# 
#     def refresh(self):
#         with codecs.open(consts.USER_CONFIG_FILE, 'r', "utf-8") as f:
#             self._props.load(f)


# Path: reggata/logic/worker_threads.py
from tarfile import TarFile
from _pyio import open
from PyQt4 import QtCore, QtGui
from reggata.data.db_schema import Thumbnail
from reggata.data.integrity_fixer import IntegrityFixerFactory
from reggata.helpers import is_none_or_empty
from reggata import memento
from reggata.user_config import UserConfig
import tarfile
import logging
import os
import traceback
import datetime
import reggata.data.commands as cmds
import reggata.errors as errors
import reggata.consts as consts
import shutil

        This thread is started every time after any query execution in Intems Table Tool.
    '''
    def __init__(self, parent, repo, items, lock, rebuild=False):
        super(ThumbnailBuilderThread, self).__init__(parent)
        self.repo = repo
        self.items = items
        self.lock = lock
        self.interrupt = False
        self.rebuild = rebuild

    def doWork(self):
        uow = self.repo.createUnitOfWork()
        try:
            thumbnail_size = int(UserConfig().get("thumbnail_size", consts.THUMBNAIL_DEFAULT_SIZE))

            for i in range(len(self.items)):
                item = self.items[i]

                if self.interrupt:
                    logger.info("ThumbnailBuilderThread interrupted!")
                    break

                if not item.data_ref or not item.data_ref.is_image():
                    continue


                if self.rebuild == False and len(item.data_ref.thumbnails) > 0:
                    continue
                elif self.rebuild:
                    #Delete ALL existing thumbnails linked with current item.data_ref from database

                    uow.session.query(Thumbnail).filter(Thumbnail.data_ref_id==item.data_ref.id)\