#!/usr/bin/env

__author__ = "Gustavo Sverzut Barbieri / Artur Duque de Souza"
__author_email__ = "barbieri@gmail.com / artur.souza@indt.org.br"
__license__ = "GPL"
__version__ = "0.3"

import os
import stat
import sys
import logging
import urllib
import gobject
import imp

import gmsconfig

log = logging.getLogger("gms.utils")
config = gmsconfig.GmsConfig()

__all__ = ("which", "load_plugins", "PluginSet", "getHTML",
           "progress_bar", "create_tid", "list_media_files")

def which(app):
    """Function to implement which(1) unix command"""
    pl = os.environ["PATH"].split(os.pathsep)
    for p in pl:
        path = os.path.join(p, app)
        if os.path.isfile(path):
            st = os.stat(path)
            if st[stat.ST_MODE] & 0111:
                return path
    return ""
# which()


def _load_module(pathlist, name):
    fp, path, desc = imp.find_module(name, pathlist)
    try:
        module = imp.load_module(name, fp, path, desc)
        return module
    finally:
        if fp:
            fp.close()
# _load_module()


class PluginSet(object):
    def __init__(self, basetype, *items):
        self.basetype = basetype
        self.map = {}
        self.list = []

        for i in items:
            self._add(i)
        self._sort()
    # __init__()


    def _add(self, item):
        self.map[item.name] = item
        self.list.append(item)
    # _add()


    def add(self, item):
        self._add()
        self._sort()
    # add()


    def __getitem__(self, spec):
        if isinstance(spec, basestring):
            return self.map[spec]
        else:
            return self.list[spec]
    # __getitem__()


    def get(self, name, default=None):
        return self.map.get(name, default)
    # get()


    def __iter__(self):
        return self.list.__iter__()
    # __iter__()


    def __len__(self):
        return len(self.list)
    # __len__()


    def _sort(self):
        self.list.sort(lambda a, b: cmp(a.priority, b.priority))
    # _sort()


    def update(self, pluginset):
        self.map.update(pluginset.map)
        self.list.extend(pluginset.list)
        self._sort()
    # update()


    def load_from_directory(self, directory):
        for i in load_plugins(directory, self.basetype):
            self._add(i)
        self._sort()
    # load_from_directory()


    def __str__(self):
        lst = []
        for o in self.list:
            lst.append('"%s" (%s)' % (o.name, o.__name__))

        return "%s(basetype=%s, items=[%s])" % \
               (self.__class__.__name__,
                self.basetype.__name__,
                ", ".join(lst))
    # __str__()
# PluginSet


def load_plugins(directory, basetype):
    """Function to load plugins from a given directory"""
    tn = basetype.__name__
    log.debug("Loading plugins from %s, type=%s" % (directory, tn))


    plugins = []
    for d in os.listdir(directory):
        if not d.endswith(".py"):
            continue

        name = d[0: -3]
        if name == "__init__":
            continue

        directory.replace(os.path.sep, ".")
        mod = _load_module([directory], name)
        for sym in dir(mod):
            cls = getattr(mod, sym)
            if isinstance(cls, type) and issubclass(cls, basetype) and \
                cls != basetype:
                plugins.append(cls)
                log.info("Loaded %s (%s) from %s" % \
                         (cls.__name__, tn, os.path.join(directory, d)))

    return plugins
# load_plugins()

def getHTML(html_file, params={}):
    """This function parses an html file with the given
    parameters and returns a formated web-page"""
    try:
        filename = os.path.join(sys.path[0], "html", html_file + ".html")
        html = open(filename).read() % params
        return html
    except Exception, e:
        return "HTML format error. Wrong keys: %s" % e

# getHTML

def _create_html_item(opt):
    """Create an <li> item using HTML."""
    return "<li>%s</li>\n" % opt
# _create_html_item

def progress_bar(value, max, barsize):
    """Creates and displays a progressbar. By OSantana"""
    chars = int(value * barsize / float(max))
    percent = int((value / float(max)) * 100)
    sys.stdout.write("#" * chars)
    sys.stdout.write(" " * (barsize - chars + 2))
    if value >= max:
        sys.stdout.write("done.\n\n")
    else:
        sys.stdout.write("[%3i%%]\r" % (percent))
        sys.stdout.flush()
    return percent
# progress_bar() by osantana

def create_tid(last_tid):
    """Function to generate TIDs (ids for transcoders).
    At first it just do +1 on last_tid but can be implemented
    to generate more sparse TIDs"""
    tid = last_tid + 1
    return tid
# create_id()

