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


class FinishHelper(L3tCommand):

    descr = "Prints useful data for finishing old incidents"

    def init_parser(self, parser):
        super(FinishHelper, self).init_parser(parser)
        parser.add_option("-i", "--incident", type="int",
                          help="incident number")
        parser.add_option("-b", "--bug", type="int",
                          help="bug number")

    def _show_for(self, incident, days):
        url = ("https://l3support.nue.suse.com/incident/%s/finish/"
               % (incident.id))
        print("%d days: %s" % (days, incident.bug_summary))
        print(url)
        bug = self.l3t.get_bug(bug_id=incident.bug_id)
        commenters = {}
        for comment in bug.comments:
            who = comment.get("who")
            commenters[who] = commenters.get(who, 0) + 1
        for commenter in sorted(commenters):
            count = commenters[commenter]
            print("  - %s: %d" % (commenter, count))

    def run(self):
        if self.opts.bug or self.opts.incident:
            incidents = [self.l3t.get_incident(incident_id=self.opts.incident,
                                               bug_id=self.opts.bug)]
        else:
            overview = self.l3t.overview(closed=True, new=False)
            incidents = overview.get("closed", [])
        now = datetime.now()
        for incident in incidents:
            delta = now - incident.ts_collect
            if ((self.opts.bug or self.opts.incident) or
                    (incident.ts_collect and delta.days > 14)):
                self._show_for(incident, delta.days)


FinishHelper().main()
