<commit_before># -*- coding: utf-8 -*-

"""
taiga_ncurses.ui.widgets.backlog
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""

import urwid

from taiga_ncurses import data

from . import mixins, generic, utils


class BacklogStats(urwid.WidgetWrap):
    def __init__(self, project):
        self.project = project
        widget = urwid.Columns([
            ("weight", 0.3, urwid.Pile([urwid.Text("")])),
            ("weight", 0.3, urwid.Pile([urwid.Text("")])),
            ("weight", 0.3, urwid.Pile([urwid.Text("")])),
        ])
        super().__init__(widget)

    def populate(self, project_stats):
        self._w = urwid.Columns([
            ("weight", 0.2, urwid.Pile([TotalPoints(project_stats), TotalMilestones(self.project)])),
            ("weight", 0.3, urwid.Pile([CompletedMilestones(self.project), CurrentMilestone(self.project)])),
            ("weight", 0.6, urwid.Pile([ClosedPoints(project_stats), DefinedPoints(project_stats)])),
        ])


class TotalPoints(urwid.Text):
    def __init__(self, project_stats):
        text = ["Total points: ", ("cyan", str(data.total_points(project_stats)))]
        super().__init__(text)


class TotalMilestones(urwid.Text):
    def __init__(self, project):
        text = ["Total milestones: ", ("cyan", str(data.total_milestones(project)))]
        super().__init__(text)


class ClosedPoints(urwid.Columns):
    def __init__(self, project_stats, **kwargs):
        text = urwid.Text(["Closed points: ", ("green", str(data.closed_points(project_stats)))])

        progressbar = urwid.ProgressBar("progressbar-normal", "progressbar-complete",
                                        data.closed_points(project_stats), data.total_points(project_stats),
                                        "progressbar-smooth")

        widget_list = [("weight", 0.4, text),
                       ("weight", 0.6, urwid.Padding(progressbar, align='center', left=2, right=2))]
        super().__init__(widget_list, **kwargs)


class DefinedPoints(urwid.Columns):
    def __init__(self, project_stats, **kwargs):
        defined_points_percentage = data.defined_points_percentage(project_stats)
        if defined_points_percentage <= 100.0:
            text = urwid.Text(["Defined points: ", ("red", str(data.defined_points(project_stats)))])
        else:
            text = urwid.Text(["Defined points: ", ("red", str(data.defined_points(project_stats))),
                               " (", ("red", "+{0:.1f} %".format(defined_points_percentage - 100.0)), ")"])

        progressbar = urwid.ProgressBar("progressbar-normal-red", "progressbar-complete-red",
                                        data.defined_points(project_stats), data.total_points(project_stats),
                                        "progressbar-smooth-red")

        widget_list = [("weight", 0.4, text),
                       ("weight", 0.6, urwid.Padding(progressbar, align='center', left=2, right=2))]
        super().__init__(widget_list, **kwargs)


class CurrentMilestone(urwid.Text):
    def __init__(self, project):
        text = [
            "Current milestone: ",
            ("cyan", str(data.current_milestone_name(project))),
        ]
        super().__init__(text)


class CompletedMilestones(urwid.Text):
    def __init__(self, project):
        text = ["Completed milestones: ", ("green", str(len(data.completed_milestones(project))))]
        super().__init__(text)


class UserStoryList(mixins.ViMotionMixin, mixins.EmacsMotionMixin, urwid.WidgetWrap):
    def __init__(self, project):
        self.project = project
        self.roles = data.computable_roles(project)

        colum_items = [("weight", 0.6, generic.ListCell("US"))]
        colum_items.append(("weight", 0.08, generic.ListCell("Status")))
        colum_items.extend([("weight", 0.05, generic.ListCell(r["name"])) for r in self.roles.values()])
        colum_items.append(("weight", 0.05, generic.ListCell(("green", "TOTAL"))))
        colum_items.append(("weight", 0.05, generic.ListCell(("cyan", "SUM."))))

        columns = urwid.Columns(colum_items)
        self.widget = urwid.Pile([columns])
        super().__init__(self.widget)

    def populate(self, user_stories, project_stats, set_focus=None):
        if user_stories:
            self.reset()

        self.doomline_limit = data.doomline_limit_points(project_stats)
        first_gains_focus = len(self.widget.contents) == 1 and user_stories

        summation = 0
        doomline = False

        for us in user_stories:
            summation += data.us_total_points(us)

            if not doomline and summation > self.doomline_limit:
                self.widget.contents.append((generic.RowDivider("red", div_char="☠"), ("weight", 0.1)))
                doomline = True

            self.widget.contents.append((UserStoryEntry(us, self.project, self.roles, summation),
                                         ("weight", 0.1)))
        # Set the focus # TODO: Refactor
        if first_gains_focus:
            if set_focus:
                for idx, item in enumerate(self.widget.contents):
                    widget, options = item
                    if type(widget) is UserStoryEntry and widget.user_story == set_focus:
                        self.widget.contents.focus = idx

            if not self.widget.contents.focus:
                self.widget.contents.focus = 1


    def reset(self):
        self.widget.contents = self.widget.contents[:1]


class UserStoryEntry(urwid.WidgetWrap):
    def __init__(self, us, project, roles, summation=0.0):
        self.user_story = us

        us_ref_and_name = "#{0: <6} {1}".format(str(data.us_ref(us)), data.us_subject(us))
        colum_items = [("weight", 0.6, generic.ListText(us_ref_and_name, align="left"))]

        hex_color, status = data.us_status_with_color(us, project)
        color = utils.color_to_hex(hex_color)
        attr = urwid.AttrSpec("h{0}".format(color), "default")
        colum_items.append(("weight", 0.08, generic.ListText( (attr, status) )))

        points_by_role = data.us_points_by_role(us, project, roles.values())
        for point in points_by_role:
            colum_items.append(("weight", 0.05, generic.ListText(str(point))))
        colum_items.append(("weight", 0.05, generic.ListText(("green", "{0:.1f}".format(
                                                                        data.us_total_points(us))))))
        colum_items.append(("weight", 0.05, generic.ListText(("cyan", "{0:.1f}".format(summation)))))

        self.widget = urwid.Columns(colum_items)
        super().__init__(urwid.AttrMap(self.widget, "default", "focus"))

    def selectable(self):
        return True

class UserStoryForm(mixins.FormMixin, urwid.WidgetWrap):
    _milestone_combo = None
    _status_combo = None
    _points_combos = {}

    def __init__(self, project, user_story={}):
        self.project = project
        self.user_story = user_story<commit_msg>Show the combo for US statuses<commit_after># -*- coding: utf-8 -*-

"""
taiga_ncurses.ui.widgets.backlog
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""

import urwid

from taiga_ncurses import data

from . import mixins, generic, utils


class BacklogStats(urwid.WidgetWrap):
    def __init__(self, project):
        self.project = project
        widget = urwid.Columns([
            ("weight", 0.3, urwid.Pile([urwid.Text("")])),
            ("weight", 0.3, urwid.Pile([urwid.Text("")])),
            ("weight", 0.3, urwid.Pile([urwid.Text("")])),
        ])
        super().__init__(widget)

    def populate(self, project_stats):
        self._w = urwid.Columns([
            ("weight", 0.2, urwid.Pile([TotalPoints(project_stats), TotalMilestones(self.project)])),
            ("weight", 0.3, urwid.Pile([CompletedMilestones(self.project), CurrentMilestone(self.project)])),
            ("weight", 0.6, urwid.Pile([ClosedPoints(project_stats), DefinedPoints(project_stats)])),
        ])


class TotalPoints(urwid.Text):
    def __init__(self, project_stats):
        text = ["Total points: ", ("cyan", str(data.total_points(project_stats)))]
        super().__init__(text)


class TotalMilestones(urwid.Text):
    def __init__(self, project):
        text = ["Total milestones: ", ("cyan", str(data.total_milestones(project)))]
        super().__init__(text)


class ClosedPoints(urwid.Columns):
    def __init__(self, project_stats, **kwargs):
        text = urwid.Text(["Closed points: ", ("green", str(data.closed_points(project_stats)))])

        progressbar = urwid.ProgressBar("progressbar-normal", "progressbar-complete",
                                        data.closed_points(project_stats), data.total_points(project_stats),
                                        "progressbar-smooth")

        widget_list = [("weight", 0.4, text),
                       ("weight", 0.6, urwid.Padding(progressbar, align='center', left=2, right=2))]
        super().__init__(widget_list, **kwargs)


class DefinedPoints(urwid.Columns):
    def __init__(self, project_stats, **kwargs):
        defined_points_percentage = data.defined_points_percentage(project_stats)
        if defined_points_percentage <= 100.0:
            text = urwid.Text(["Defined points: ", ("red", str(data.defined_points(project_stats)))])
        else:
            text = urwid.Text(["Defined points: ", ("red", str(data.defined_points(project_stats))),
                               " (", ("red", "+{0:.1f} %".format(defined_points_percentage - 100.0)), ")"])

        progressbar = urwid.ProgressBar("progressbar-normal-red", "progressbar-complete-red",
                                        data.defined_points(project_stats), data.total_points(project_stats),
                                        "progressbar-smooth-red")

        widget_list = [("weight", 0.4, text),
                       ("weight", 0.6, urwid.Padding(progressbar, align='center', left=2, right=2))]
        super().__init__(widget_list, **kwargs)


class CurrentMilestone(urwid.Text):
    def __init__(self, project):
        text = [
            "Current milestone: ",
            ("cyan", str(data.current_milestone_name(project))),
        ]
        super().__init__(text)


class CompletedMilestones(urwid.Text):
    def __init__(self, project):
        text = ["Completed milestones: ", ("green", str(len(data.completed_milestones(project))))]
        super().__init__(text)


class UserStoryList(mixins.ViMotionMixin, mixins.EmacsMotionMixin, urwid.WidgetWrap):
    def __init__(self, project):
        self.project = project
        self.roles = data.computable_roles(project)

        colum_items = [("weight", 0.6, generic.ListCell("US"))]
        colum_items.append(("weight", 0.08, generic.ListCell("Status")))
        colum_items.extend([("weight", 0.05, generic.ListCell(r["name"])) for r in self.roles.values()])
        colum_items.append(("weight", 0.05, generic.ListCell(("green", "TOTAL"))))
        colum_items.append(("weight", 0.05, generic.ListCell(("cyan", "SUM."))))

        columns = urwid.Columns(colum_items)
        self.widget = urwid.Pile([columns])
        super().__init__(self.widget)

    def populate(self, user_stories, project_stats, set_focus=None):
        if user_stories:
            self.reset()

        self.doomline_limit = data.doomline_limit_points(project_stats)
        first_gains_focus = len(self.widget.contents) == 1 and user_stories

        summation = 0
        doomline = False

        for us in user_stories:
            summation += data.us_total_points(us)

            if not doomline and summation > self.doomline_limit:
                self.widget.contents.append((generic.RowDivider("red", div_char="☠"), ("weight", 0.1)))
                doomline = True

            self.widget.contents.append((UserStoryEntry(us, self.project, self.roles, summation),
                                         ("weight", 0.1)))
        # Set the focus # TODO: Refactor
        if first_gains_focus:
            if set_focus:
                for idx, item in enumerate(self.widget.contents):
                    widget, options = item
                    if type(widget) is UserStoryEntry and widget.user_story == set_focus:
                        self.widget.contents.focus = idx

            if not self.widget.contents.focus:
                self.widget.contents.focus = 1


    def reset(self):
        self.widget.contents = self.widget.contents[:1]


class UserStoryEntry(urwid.WidgetWrap):
    def __init__(self, us, project, roles, summation=0.0, on_status_change=None, on_point_change=None):
        self.user_story = us

        us_ref_and_name = "#{0: <6} {1}".format(str(data.us_ref(us)), data.us_subject(us))
        colum_items = [("weight", 0.6, generic.ListText(us_ref_and_name, align="left"))]

        us_statuses = data.us_statuses(project)
        items = tuple(((urwid.AttrSpec("h{0}".format(utils.color_to_hex(s.get("color", "#ffffff"))), "default"),
                        s.get("name", "")), s.get("id", None)) for s in us_statuses.values())
        selected = us.get("status", None) or project.get("default_us_status", None)
        status_combo = generic.ComboBox(items, selected_value=selected, style="cyan", enable_markup=True,
                                        on_state_change=on_status_change, user_data=us)
        colum_items.append(("weight", 0.08, status_combo))

        points_by_role = data.us_points_by_role(us, project, roles.values())
        for point in points_by_role:
            colum_items.append(("weight", 0.05, generic.ListText(str(point))))
        colum_items.append(("weight", 0.05, generic.ListText(("green", "{0:.1f}".format(
                                                                        data.us_total_points(us))))))
        colum_items.append(("weight", 0.05, generic.ListText(("cyan", "{0:.1f}".format(summation)))))

        self.widget = urwid.Columns(colum_items)
        super().__init__(urwid.AttrMap(self.widget, "default", "focus"))

    def selectable(self):
        return True

class UserStoryForm(mixins.FormMixin, urwid.WidgetWrap):
    _milestone_combo = None
    _status_combo = None
    _points_combos = {}

    def __init__(self, project, user_story={}):
        self.project = project
        self.user_story = user_story
{'fraction_non_alphanumeric': 0.14925163375729042, 'fraction_numerical': 0.011383599184878083, 'mean_word_length': 2.6604938271604937, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 21, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1768519', 'n_tokens_mistral': 4481, 'n_tokens_neox': 4250, 'n_words': 747}