import sublime
from os.path import dirname, basename

from .core import packages_with_overrides, log
from .core import PackageListCollectionThread


###---------------------------------------------------------------------------


# When annotation is turned on in the resource browser, this is the annotation
# that is appended to the end of the resources that are currently overridden.
_annotation = " [*Override*]"


###---------------------------------------------------------------------------


class ResourceType():
    """
    This class acts as a simple enumeration of the different styles of
    resources that you can browse using the other classes in this module.
    """
    OVERRIDE = 1
    NONOVERRIDE = 2
    ALL = 3


###---------------------------------------------------------------------------


class PackageBrowser():
    """
    Provide the ability to browse for a package among all known packages. The
    browse can be filtered to show all packages (ALL) or only those packages
    that contain at least one override (OVERRIDE) as desired. The NONOVERRIDE
    option is treated as ALL for the purposes of this class.

    If a filter is provided, it will be invoked once for each package in the
    list to see if the package should be presented; this trumps the file_type
    argument.
    """
    def __init__(self, window=None, file_type=ResourceType.ALL, p_filter=None):
        self.window = window or sublime.active_window()
        self.file_type = file_type
        self.p_filter = p_filter

    def _get_contents(self, pkg_list):
        if self.p_filter:
            return [name for name, pkg in pkg_list if self.p_filter(pkg)]

        if self.file_type == ResourceType.OVERRIDE:
            return packages_with_overrides(pkg_list)
        else:
            return [name for name, pkg in pkg_list]

    def browse(self, pkg_list, on_done):
        """
        Allows the user to select a package from the package list provided,
        filtering the list to the criteria set in the file_type attribute.

        on_done will be called with the name of the package selected, which can
        be None if the panel was cancelled or no packages were found.
        """
        items = self._get_contents(pkg_list)
        if not items: