#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Fournit quelques outils pour le plugin Python"""

import os
import logging
import cStringIO
import traceback

LOGGER = logging.getLogger('Bcfg2.Plugins.Python')

COLOR_CODE = {
    'grey': 30,
    'red': 31,
    'green': 32,
    'yellow': 33,
    'blue': 34,
    'purple': 35,
    'cyan': 36,
}

BCFG2_DEBUG = os.getenv("BCFG2_DEBUG")
BCFG2_DEBUG_COLOR = os.getenv("BCFG2_DEBUG_COLOR")

def debug(message, logger, color=None):
    """Stocke dans un logger les messages de debug"""
    if not BCFG2_DEBUG:
        return

    if BCFG2_DEBUG_COLOR and color:
        logger.info("\033[1;%dm%s\033[0m" % (COLOR_CODE[color], message))
    else:
        logger.info(message)

def log_traceback(fname, section, exn, logger):
    """En cas de traceback, on le loggue sans faire planter
    le serveur bcfg2"""
    logger.error('Python %s error: %s: %s: %s' % (section, fname, str(exn.__class__).split('.', 2)[1], str(exn)))

    stream = cStringIO.StringIO()
    traceback.print_exc(file=stream)

    for line in stream.getvalue().splitlines():
        logger.error('Python %s error: -> %s' % (section, line))

class PythonIncludePaths(object):
    """C'est un objet qui stocke les dossier d'inclusion python"""
    includes = []

    @classmethod
    def get(cls, index, default):
        """Retourne includes[index] ou default"""
        if len(cls.includes) > index:
            return cls.includes[index]
        return default

    @classmethod
    def append(cls, value):
        """Ajoute une valeur à la liste"""
        cls.includes.append(value)

    @classmethod
    def remove(cls, value):
        """Retire une valeur à la liste"""
        if value in cls.includes:
            cls.includes.remove(value)

    @classmethod
    def pop(cls, index):
        """Vire un index si existant"""
        if len(cls.includes) > index:
            return cls.includes.pop(index)

