from typing import Dict

from staff.headcounts.headcounts_summary.query_builder.query_params import QueryParams, RelatedEntity
from staff.headcounts.headcounts_summary.query_builder.query_results import Result


class EmptySummaryFilter:
    def __init__(self, query_params: QueryParams) -> None:
        self._query_params = query_params

    def filter(self, result: Result) -> None:
        if RelatedEntity.value_stream not in self._query_params.groupings:
            return

        self._filter(result)

    def _filter(self, current_result_level: Result) -> None:
        self._check_and_remove_if_necessary(current_result_level.next_level_grouping)
        self._check_and_remove_if_necessary(current_result_level.children)

    def _check_and_remove_if_necessary(self, items: Dict[int, Result]) -> None:
        for grouping_entity_id in list(items.keys()):
            result = items[grouping_entity_id]
            if result.current_level_grouping == RelatedEntity.value_stream.value:
                if self._entity_should_be_removed(result):
                    items.pop(grouping_entity_id)

    def _entity_should_be_removed(self, grouping: Result) -> bool:
        return grouping.summary.headcount == 0
