import importlib
import os
import glob
import sys
import types
import filetypes
from filetypes.base import FileTypeAnalyzer, ParsingError

REGEX_MAX_SCOPE = 256

def get_analyzers(data_dir, user_data_dir, reload_plugins=False):
    fileanalyzers = []
    seen = set()
    if user_data_dir and user_data_dir != data_dir:
        toscan = (user_data_dir, data_dir)
    else:
        toscan = (data_dir,)
    for plugins_path in toscan:
        for fname in glob.glob(os.path.join(plugins_path, "filetypes", "*.py")):
            module_name = os.path.relpath(fname, plugins_path)[:-3].replace(os.sep, ".")
            if module_name in sys.modules:
                mod = sys.modules[module_name]
                if reload_plugins:
                    for element in dir(mod):
                        if isinstance(element, types.ModuleType):
                            importlib.reload(element)
                    mod = importlib.reload(mod)
            else:
                mod = importlib.import_module(module_name)
            for elemname in dir(mod):
                elem = getattr(mod, elemname)
                try:
                    if issubclass(elem, FileTypeAnalyzer) and elem != FileTypeAnalyzer and not elemname in seen:
                        fileanalyzers.append(elem)
                        seen.add(elemname)
                except TypeError: pass
    return sorted(fileanalyzers, key=lambda x: x.name)


def analyze(file, file_analyzer_class, hint="", confirm=False, lazy=False):
    scanner = file_analyzer_class()
    result = None
    try:
        result = scanner.run(file, hint, confirm, lazy)
    except ParsingError as e:
        pass
    return result, scanner
