import attr
from typing import Dict, List

from django.db import connections, router

from staff.headcounts.headcounts_summary import headcount_queries_v2  # type: ignore

from staff.departments.models import Department


@attr.s(auto_attribs=True)
class DepartmentCounters:
    total_hc: int = 0
    current_count: int = 0
    offers: int = 0

    current_balance: int = 0

    vacancy_open: int = 0

    vacancy_plan: int = 0
    vacancy_plan_new: int = 0
    vacancy_plan_replacement: int = 0

    reserve_new: int = 0

    crossheadcount: int = 0
    replacement_to_working: int = 0
    offers_for_working_replacement: int = 0
    vacancy_open_for_working_replacement: int = 0
    vacancy_plan_for_working_replacement: int = 0

    overdraft_percents_with_child: int = 0


class HeadcountsSummaryCalculator:
    def __init__(self, valuestream_mode: bool = False):
        self.valuestream_mode = valuestream_mode
        self.queries = headcount_queries_v2
        self.cursor = connections[router.db_for_read(Department)].cursor()

    def get_summary_for_departments(
        self,
        departments_ids: List,
        summary_with_children: bool,
    ) -> Dict[int, DepartmentCounters]:
        if summary_with_children:
            return self._total_departments_counters(departments_ids)

        return self._departments_counters(departments_ids)

    def _total_departments_counters(self, all_ids) -> Dict[int, DepartmentCounters]:
        query = (
            self.queries.NESTED_VALUESTREAM_COUNTERS_QUERY  # type: ignore
            if self.valuestream_mode else
            self.queries.NESTED_DEPARTMENTS_COUNTERS_QUERY  # type: ignore
        )
        self.cursor.execute(query, (tuple(all_ids), ))
        return self._cursors_results_to_dict()

    def _departments_counters(self, all_ids) -> Dict[int, DepartmentCounters]:
        query = (
            self.queries.VALUESTREAM_COUNTERS_QUERY  # type: ignore
            if self.valuestream_mode else
            self.queries.DEPARTMENTS_COUNTERS_QUERY  # type: ignore
        )
        self.cursor.execute(query, (tuple(all_ids), ))
        return self._cursors_results_to_dict()

    def _cursors_results_to_dict(self) -> Dict[int, DepartmentCounters]:
        result = {}

        for row in self.cursor.fetchall():
            result[row[0]] = DepartmentCounters(*row[1:])

        return result
