#!/usr/bin/python3 -s
import textwrap
from l3tlib.command import L3tCommand


class AllRecentComments(L3tCommand):

    descr = "Shows the last comment of every bug handled"

    def run(self):
        incidents = self.l3t.overview(active=True, processed=True,
                                      sleeping=True, new=False)
        comment_wrapper = textwrap.TextWrapper(width=79, initial_indent="    ",
                                               subsequent_indent="   ")
        for group in ("active", "processed", "sleeping"):
            for incident in incidents[group]:
                bug = self.l3t.get_bug(bug_id=incident.bug_id)
                comment = bug.comments[-1]
                flags = (" [%s]" % ",".join(("%s=%s" % (f.get("name"),
                                             f.get("requestee", "anyone"))
                                             for f in bug.flags))
                         if bug.flags else "")
                bug_line = " [%s] %s%s" % (bug.bug_id, bug.short_desc, flags)
                raw_comment = comment.get("thetext")
                lines = [line for line in raw_comment.splitlines()
                         if not line.startswith(">")]
                comment_part = "\n".join(lines)[:1024]
                wrap_block = "%s %s" % (comment["bug_when"], comment_part)
                print(bug_line)
                print()
                print("\n".join(comment_wrapper.wrap(wrap_block)))
                print()
                print()


AllRecentComments().main()
