# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).

from odoo import _, http
from odoo.exceptions import AccessError, MissingError
from odoo.http import request

from odoo.addons.portal.controllers.portal import CustomerPortal
from odoo.addons.portal.controllers.portal import pager as portal_pager


class EventRegistrationPortal(CustomerPortal):

    def _prepare_home_portal_values(self, counters):
        values = super()._prepare_home_portal_values(counters)
        if "event_count" in counters:
            Registration = request.env["event.registration"]
            partner = request.env.user.partner_id
            domain = self._get_event_registration_domain(partner)
            values["event_count"] = (
                Registration.search_count(domain)
                if Registration.has_access("read")
                else 0
            )
        return values

    def _get_event_registration_domain(self, partner):
        return [
            ("partner_id", "child_of", [partner.commercial_partner_id.id]),
            ("state", "!=", "cancel"),
        ]

    def _get_event_searchbar_sortings(self):
        return {
            "date": {"label": _("Event Date"), "order": "event_begin_date desc"},
            "name": {"label": _("Event Name"), "order": "event_id asc"},
            "state": {"label": _("Status"), "order": "state asc"},
        }

    @http.route(
        ["/my/events", "/my/events/page/<int:page>"],
        type="http",
        auth="user",
        website=True,
    )
    def portal_my_events(self, page=1, sortby=None, **kw):
        partner = request.env.user.partner_id
        Registration = request.env["event.registration"]
        domain = self._get_event_registration_domain(partner)

        searchbar_sortings = self._get_event_searchbar_sortings()
        if not sortby:
            sortby = "date"
        order = searchbar_sortings[sortby]["order"]

        total = (
            Registration.search_count(domain) if Registration.has_access("read") else 0
        )
        pager = portal_pager(
            url="/my/events",
            url_args={"sortby": sortby},
            total=total,
            page=page,
            step=self._items_per_page,
        )
        registrations = (
            Registration.search(
                domain,
                order=order,
                limit=self._items_per_page,
                offset=pager["offset"],
            )
            if Registration.has_access("read")
            else Registration
        )

        request.session["my_events_history"] = registrations.ids[:100]

        values = self._prepare_portal_layout_values()
        values.update(
            {
                "registrations": registrations,
                "page_name": "event",
                "pager": pager,
                "sortby": sortby,
                "searchbar_sortings": searchbar_sortings,
                "default_url": "/my/events",
            }
        )
        return request.render("portal_event_registration.portal_my_events", values)

    @http.route(
        ["/my/events/<int:registration_id>"],
        type="http",
        auth="user",
        website=True,
    )
    def portal_my_event_detail(self, registration_id, access_token=None, **kw):
        try:
            registration_sudo = self._document_check_access(
                "event.registration", registration_id, access_token=access_token
            )
        except (AccessError, MissingError):
            return request.redirect("/my")

        values = self._prepare_portal_layout_values()
        values["registration"] = registration_sudo
        values = self._get_page_view_values(
            registration_sudo,
            access_token,
            values,
            "my_events_history",
            False,
            **kw,
        )
        return request.render(
            "portal_event_registration.portal_my_event_detail", values
        )
