# -*- coding: utf-8 -*-

import re
from commands import getstatusoutput,getoutput


def execute(macro, text) :

    descriptions = {}
    with open('/usr/scripts/var/autostatus/hosts', 'r') as f:
        for line in f.readlines():
            line = line.split(' ', 4)
            host = line[0]
            try:
                dec = line[4].decode('utf-8', errors='ignore')
            except IndexError:
                dec = u"N/A"
            dec = dec.strip()
            descriptions[host] = u'%s' % host
            if dec:
                descriptions[host] += u' (%s)' % dec

    lines = open('/usr/scripts/var/local.status').readlines()

    f = macro.formatter
    code = f.table(1)

    typlist =  ['routes', 'serveurs', 'serveurs de la ferme', 'switches', 'bornes', u'services extérieurs au crans']

    for typ in typlist:
        lines = lines [1:]
        trucsdown = ''

        while lines and not re.match('dummy_host_\d+ 0 \n', lines[0]):
            if not re.search(' 0 ', lines[0]):
                line = lines[0].split(' ')
                trucsdown += f.table_row(1)
                trucsdown += f.table_cell(1,{'style':'background-color:lightgrey; color: black;'})
                trucsdown += f.text(descriptions.get(line[0], line[0]))
                trucsdown += f.table_cell(0)
                # nombre de non réponse au ping
                if int(line[1]) > 2 :
                    trucsdown += f.table_cell(1,{'style':'background-color:red; color: black;'})
                    trucsdown += f.text(u'down')
                else :
                    trucsdown += f.table_cell(1,{'style':'background-color:blue;'})
                    trucsdown += f.text(u'état incertain')
                trucsdown += f.table_cell(0)
                trucsdown += f.table_row(0)
            lines = lines [1:]

        if trucsdown == '':
            code += f.table_row(1)
            code += f.table_cell(1, {'style':'background-color:silver; color: black;'})
            code += f.text(u'Autostatus des '+typ)
            code += f.table_cell(0)
            code += f.table_cell(1, {'style':'background-color:lime; color: black;'})
            code += f.text(u'OK')
            code += f.table_cell(0)
            code += f.table_row(0)
        else:
            code += f.table_row(1)
            code += f.table_cell(1, {'style':'background-color:silver; color:black;', 'colspan':'2' })
            code += f.text(u'Autostatus des '+typ)
            code += f.table_cell(0)
            code += f.table_row(0)
            code += f.table_row(1)
            code += f.table_cell(1, {'style':'background-color:aliceblue', 'colspan':'2'})
            code += f.table(1) + trucsdown + f.table(0)
            code += f.table_cell(0)
            code += f.table_row(0)
            trucsdown = ''

    code += f.table(0)
    return code
