#!/usr/bin/env python

__author__ = "Artur Duque de Souza"
__author_email__ = "artur.souza@indt.org.br"
__license__ = "GPL"
__version__ = "0.1"

import os
import logging

__all__ = ("Log", "log_structure")

class log_structure(object):
    """Structure to hold log info."""

    def __init__(self, log=None):
        self.log = log
        self.history = []
    # __init__()

# log_structure()

class Log(object):
    """This class implements a log where we can store status of
    all transcoders (even from those that are not running any more)."""

    ## key = tid
    ## item = ls
    logs = {}

    def insert(self, tid, name):
        """Insert a given tid on the log structure"""
        if not self.logs.has_key(tid):
            self.logs[tid] = log_structure(logging.getLogger(name))
            return True
        else:
            return False
    # insert()

    def remove(self, tid=None):
        """Cleans up all log stored for a
        given tid or for all transcodes."""
        if not tid:
            self.logs = {}
        else:
            del(self.logs[tid])

        return True
    # clean()

    def get_status(self, tid=None, all=False):
        """Get the status of all transcoders or
        of just one of them if it's given an tid."""
        if not tid:
            ret = {}
            for tids, logs in self.logs.items():
                if len(logs.history) > 0:
                    if not all:
                        ret[tids] = logs.history[-1]
                    else:
                        ret[tids] = logs.history
            return ret
        elif self.logs.has_key(tid) and len(self.logs[tid].history) > 0:
            if not all:
                return self.logs[tid].history[-1]
            else:
                return self.logs[tid].history

        return False
    # get_status()

    def _update_status(self, tid=None, msg=""):
        """Update the status of a given tid. Private method that
        is only called inside error/info/debug wrappers"""
        if msg != "":
            self.logs[tid].history.append(msg)
            return True
        else:
            return False
    # update_status()

    def error(self, tid, msg):
        """Python's Log.error wrapper"""
        if self.logs.has_key(tid):
            self.logs[tid].log.error("%s" % msg)
            return self._update_status(tid, msg)
        else:
            return False
    # error()

    def info(self, tid, msg):
        """Python's Log.info wrapper"""
        if self.logs.has_key(tid):
            self.logs[tid].log.info("%s" % msg)
            self._update_status(tid, msg)
            return True
        else:
            return False
    # info()

    def debug(self, tid, msg):
        """Python's Log.debug wrapper"""
        if self.logs.has_key(tid):
            self.logs[tid].log.debug("%s" % msg)
            self._update_status(tid, msg)
            return True
        else:
            return False
    # debug()
