#!/usr/bin/python
import textwrap
from l3tlib.command import L3tCommand, L3tIncidentStateMixIn
from l3tlib.util import wrapping_box
from l3tlib.template import format_objects, format, make_color_helper


class L3ls(L3tIncidentStateMixIn, L3tCommand):

    descr = "Lists incidents"

    def init_parser(self, parser):
        super(L3ls, self).init_parser(parser)
        parser.add_option("-H", "--no-header", dest="headers",
                          default=True, action="store_false",
                          help="Don't print section headers")

    def print_section(self, description, incidents):
        if not incidents:
            return

        should_wrap, wrap_width = wrapping_box(self.config)
        wrapper = textwrap.TextWrapper(width=wrap_width,
                                       subsequent_indent="       ")
        if self.opts.headers:
            header = format(self.config.l3t.incidents_header,
                            count=len(incidents), description=description,
                            padding="", C=make_color_helper(self.config))
            line = header.rjust(wrap_width, self.config.l3t.incidents_padding)
            print line
        formatted_incidents = format_objects(self.config.l3t.incident_oneline,
                                             incidents,
                                             C=make_color_helper(self.config))
        for incident, repr_incident in formatted_incidents:
            if should_wrap:
                output = "\n".join(wrapper.wrap(repr_incident))
            else:
                output = repr_incident
            print output

    def run(self):
        incidents = self.l3t.overview(active=self.opts.active,
                                      processed=self.opts.processed,
                                      sleeping=self.opts.sleeping,
                                      new=self.opts.new,
                                      backup=self.opts.backup,
                                      closed=self.opts.closed)
        if incidents.get("closed"):
            self.print_section("closed incidents",
                               incidents.get("closed", []))
        if incidents.get("sleeping"):
            self.print_section("sleeping incidents",
                               incidents.get("sleeping", []))
        if incidents.get("backup"):
            self.print_section("incidents need backup",
                               incidents.get("backup", []))
        if incidents.get("processed"):
            self.print_section("processed incidents",
                               incidents.get("processed", []))
        if incidents.get("active"):
            self.print_section("active incidents",
                               incidents.get("active", []))
        if incidents.get("new"):
            self.print_section("new incidents",
                               incidents.get("new", []))


L3ls().main()
