import calendar
import datetime

from odoo import api, models


class XenoOrrDashboard(models.AbstractModel):
    """Home dashboard data (Section 2). No stored data of its own -- a thin
    aggregation layer over xeno.orr.request/reimbursement, same shape as
    xeno_hr_dashboard's own xeno.hr.dashboard."""

    _name = "xeno.orr.dashboard"
    _description = "Outside Request & Reimbursement Dashboard"

    def _xeno_stats(self, employee_ids, date_from, date_to):
        Request = self.env["xeno.orr.request"].sudo()
        domain = [
            ("employee_id", "in", employee_ids),
            ("datetime_leaving", ">=", date_from),
            ("datetime_leaving", "<=", date_to),
        ]
        requests = Request.search(domain)
        with_reimbursement = requests.filtered("reimbursement_ids")
        reimburse_amount = sum(with_reimbursement.mapped("current_reimbursement_id.total_amount"))
        return {
            "total_requests": len(requests),
            "outside_only": len(requests) - len(with_reimbursement),
            "reimburse_requests": len(with_reimbursement),
            "reimburse_amount": reimburse_amount,
        }

    def _xeno_trend(self, employee_ids):
        """Last 6 months, fixed (Section 2: "not filterable")."""
        today = datetime.date.today()
        months = []
        year, month = today.year, today.month
        for _i in range(6):
            months.append((year, month))
            month -= 1
            if month == 0:
                month = 12
                year -= 1
        months.reverse()

        Request = self.env["xeno.orr.request"].sudo()
        trend = []
        for year, month in months:
            last_day = calendar.monthrange(year, month)[1]
            date_from = "%04d-%02d-01 00:00:00" % (year, month)
            date_to = "%04d-%02d-%02d 23:59:59" % (year, month, last_day)
            count = Request.search_count([
                ("employee_id", "in", employee_ids),
                ("datetime_leaving", ">=", date_from),
                ("datetime_leaving", "<=", date_to),
            ])
            trend.append({"label": "%04d-%02d" % (year, month), "total": count})
        return trend

    @api.model
    def get_dashboard_data(self, date_from, date_to):
        user = self.env.user
        employee = user.employee_id
        is_management = user.has_group("xeno_orr.group_orr_management")
        is_finance = user.has_group("xeno_orr.group_orr_finance")
        team_employees = self.env["hr.employee"].sudo().search([("parent_id", "=", employee.id)])
        is_supervisor = bool(team_employees)

        own = self._xeno_stats([employee.id], date_from, date_to)

        team = None
        if is_supervisor:
            team = self._xeno_stats(team_employees.ids, date_from, date_to)

        all_data = None
        if is_management or is_finance:
            all_employees = self.env["hr.employee"].sudo().search([("active", "=", True)])
            all_data = self._xeno_stats(all_employees.ids, date_from, date_to)

        if is_management or is_finance:
            trend_scope = self.env["hr.employee"].sudo().search([("active", "=", True)]).ids
        elif is_supervisor:
            trend_scope = team_employees.ids
        else:
            trend_scope = [employee.id]

        return {
            "role": {
                "is_supervisor": is_supervisor,
                "is_management": is_management,
                "is_finance": is_finance,
            },
            "own": own,
            "team": team,
            "all": all_data,
            "trend": self._xeno_trend(trend_scope),
        }
