# -*- coding: UTF-8 -*-
"""
utilitaires d'affichage sur la ligne de commande
"""
import sys
from os import system, environ
from pyeole.process import system_out


if sys.version_info[0] >= 3:
    unicode = str


NOTPUT=False
code, out, err = system_out(['/usr/bin/tput', 'hpa', '60'])
if code != 0:
    NOTPUT=True

def print_color(string, color=(0, 'black'), newline=True):
    """
    (man terminfo)
    black     COLOR_BLACK       0     0, 0, 0
    blue      COLOR_BLUE        1     0,0,max
    green     COLOR_GREEN       2     0,max,0
    cyan      COLOR_CYAN        3     0,max,max
    red       COLOR_RED         4     max,0,0
    magenta   COLOR_MAGENTA     5     max,0,max
    yellow    COLOR_YELLOW      6     max,max,0
    white     COLOR_WHITE       7     max,max,max

    default                     9
    """
    color_code, color_name = color
    # si la variable shell ModeTxt est à "yes", on affiche sans mise en forme
    if NOTPUT or environ.get('ModeTxt','no') == 'yes':
        print(string)
    elif environ.get('ModeEad','no') == 'yes':
        print("""<font color="%s"> %s </font><br>""" % (color_name, string.replace('\n','<br>\n').replace('\t','&nbsp;')))
    else:
        cmd = []
        if sys.version_info[0] < 3 and isinstance(string, unicode):
            string = string.encode('utf8')
        for line in string.splitlines():
            cmd.append("""echo \"%s\" """ % line.replace('"', '\\"').replace('`', '\\`'))
        if not newline:
            cmd[-1] = cmd[-1].replace('echo "', 'echo -n "')
        if environ.get('ModeTxt','no') != 'yes':
            cmd.insert(0, "tput setaf %d" % color_code)
            cmd.append("tput op")
        system("\n".join(cmd))

def print_red(string, newline=True):
    """ affichage rouge """
    print_color(string, (1, 'red'), newline)

def print_green(string, newline=True):
    """ affichage vert """
    print_color(string, (2, 'green'), newline)

def print_orange(string, newline=True):
    """ affichage orange """
    print_color(string, (3, 'orange'), newline)

def print_blue(string, newline=True):
    """ affichage bleu """
    print_color(string, (4, 'blue'), newline)

def print_magenta(string, newline=True):
    """ affichage magenta """
    print_color(string, (5, 'magenta'), newline)

def print_cyan(string, newline=True):
    """ affichage cyan """
    print_color(string, (6, 'cyan'), newline)

def print_white(string, newline=True):
    """ affichage blanc """
    print_color(string, (7, 'white'), newline)

def print_title(string):
    print_cyan('\n*** %s ***' % string)
