# -*- coding: utf-8 -*-

import regex, collections, os, logging, traceback
from PyQt5.Qt import QIcon, QPixmap
from calibre.ebooks.oeb.polish.container import OEB_DOCS, OEB_STYLES
from calibre.ebooks.oeb.base import NCX_MIME
from calibre.utils.config import config_dir

LOGPATH = os.path.join(config_dir, 'plugins', 'typexlog.txt')

logger_gen = logging.getLogger('general_logger')
log_handler1 = logging.FileHandler(LOGPATH)
formatter = logging.Formatter('%(message)s')
log_handler1.setFormatter(formatter)
logger_gen.setLevel(logging.INFO)
logger_gen.addHandler(log_handler1)


def myexcepthook(_type, value, tb):
        rawreport = traceback.format_exception(_type, value, tb)
        report = '\n'.join(rawreport)
        errorlog = open(LOGPATH, 'a')
        errorlog.write(('%s\n' + '-' * 30 + '\n\n') % report)
        errorlog.close()


def log(*x):
    logger_gen.info(x)


def anon(path):
    if 'calibre-cache' in path :
        return path.split('calibre-cache')[-1]
    elif 'calibre' in path :
        return path.split('calibre')[-1]
    return path


class OrderedSet(collections.MutableSet):

    def __init__(self, iterable=None):
        self.end = end = []
        end += [None, end, end]  # sentinel node for doubly linked list
        self.map = {}  # key --> [key, prev, next]
        if iterable is not None:
            self |= iterable

    def __len__(self):
        return len(self.map)

    def __contains__(self, key):
        return key in self.map

    def add(self, key):
        if key not in self.map:
            end = self.end
            curr = end[1]
            curr[2] = end[1] = self.map[key] = [key, curr, end]

    def discard(self, key):
        if key in self.map:
            key, prev, next = self.map.pop(key)
            prev[2] = next
            next[1] = prev

    def __iter__(self):
        end = self.end
        curr = end[2]
        while curr is not end:
            yield curr[0]
            curr = curr[2]

    def __reversed__(self):
        end = self.end
        curr = end[1]
        while curr is not end:
            yield curr[0]
            curr = curr[1]

    def pop(self, last=True):
        if not self:
            raise KeyError('set is empty')
        key = self.end[1][0] if last else self.end[2][0]
        self.discard(key)
        return key

    def __repr__(self):
        if not self:
            return '%s()' % (self.__class__.__name__,)
        return '%s(%r)' % (self.__class__.__name__, list(self))

    def __eq__(self, other):
        if isinstance(other, OrderedSet):
            return len(self) == len(other) and list(self) == list(other)
        return set(self) == set(other)


def polish_text(x):
    x = regex.sub('\x20', _('{esp}'), x, flags=regex.UNICODE)
    x = regex.sub('\xa0', _('{ins}'), x, flags=regex.UNICODE)
    return x


def load_resources(name):
    import zipfile
    from calibre_plugins.typex.main import PLUGIN_PATH
    ans = ''
    with zipfile.ZipFile(PLUGIN_PATH, 'r') as zf:
        for candidate in zf.namelist():
            if candidate == name:
                ans = zf.read(candidate)
    return ans


def get_icon(name):
    pixmap = QPixmap()
    pixmap.loadFromData(load_resources(name))
    return QIcon(pixmap)


def comment_reader():
    from calibre_plugins.typex.main import COMMENTS_PATH
    from calibre.constants import iswindows
    file = COMMENTS_PATH
    sep = '\n' if iswindows else '\r\n'
    local = COMMENTS_PATH.split('.')[0] + '.local'
    if os.path.isfile(local):
        file = local
    with open(file, mode='r') as f :
        l = f.readlines()
    it = iter([x.strip(sep) for x in l if not (x.startswith(('#')) or x == sep)])
    com = {}
    try :
        val = next(it)
    except StopIteration:
        return com
    while True :
        text = ''
        if val.startswith('['):
            key = val
            icon = next(it)
            while True:
                try :
                    val = next(it)
                    if not val.startswith('['):
                        text += sep + val
                    else:
                        com[key] = (icon, text.lstrip(sep))
                        break
                except StopIteration:
                    com[key] = (icon, text.lstrip(sep))
                    break
        else:
            break
    return com


def check_dictionary():
    from calibre.spell.dictionary import custom_dictionaries
    for cus in custom_dictionaries() :
        dic_lang = cus.primary_locale.langcode  # 'fra' for french
        dic_name = cus.name
        dic_version = cus.name.split('v')[-1]

