# -*- coding: UTF-8 -*-
# Copyright 2016 Red Hat, Inc.
# Part of clufter project
# Licensed under GPLv2+ (a copy included | http://gnu.org/licenses/gpl-2.0.txt)
"""Common base for testing"""
__author__ = "Jan Pokorný <jpokorny @at@ Red Hat .dot. com>"


from os.path import join, dirname as d; execfile(join(d(d((__file__))), '_go'))


from os.path import dirname, join, split
from sys import modules
from unittest import TestCase

from .filter_manager import FilterManager
from .utils import filterdict_keep


def rewrite_root(flt, new_root, **kwargs):
    # /foo/bar -> (/foo, bar)
    # /foo/bar/ -> (/foo/bar, )
    new_root_dir, new_xml_root = split(new_root)
    old_root_dir = dirname(modules[flt.__class__.__module__].__file__)
    new_root_dir = join(old_root_dir, new_root_dir)

    def _wrap(flt_cls):
        fnc = flt_cls._fnc
        def _fnc_wrapper(flt_ctxt, *args, **kws):
            flt_ctxt.update(
                filterdict_keep(kwargs, 'walk_transform',
                               root_dir=new_root_dir, xml_root=new_xml_root)
            )
            return fnc(flt_ctxt, *args, **kws)
        return _fnc_wrapper
    flt._fnc = _wrap(flt)
    return flt


class CommonFilterTestCase(TestCase):
    def setUp(self):
        self.flt_mgr = FilterManager.init_lookup(ext_plugins=False)


class TeardownFilterTestCase(CommonFilterTestCase):
    def tearDown(self):
        self.flt_mgr.registry.setup(True)  # start from scratch
        self.flt_mgr = None
