from plone import api
from plone.memoize.view import memoize_contextless
from ploneintranet import api as pi_api
from ploneintranet.core import _
from ploneintranet.layout.browser.base import BaseView
from ploneintranet.layout.interfaces import IDiazoAppTemplate
from zope.interface import implementer


@implementer(IDiazoAppTemplate)
class View(BaseView):
    @property
    @memoize_contextless
    def user(self):
        """The current user (if we have one authenticated), or None"""
        return pi_api.userprofile.get_current()

    @property
    def userid(self):
        if not self.user:
            return ""
        return self.user.getId()

    @property
    def talks(self):
        return self.context.listFolderContents(
            {"portal_type": "ploneintranet.conference.talk"}
        )


class MaybeAttend(BaseView):
    """"""

    @property
    @memoize_contextless
    def user(self):
        """The current user (if we have one authenticated), or None"""
        return pi_api.userprofile.get_current()

    @property
    def userid(self):
        if not self.user:
            return ""
        return self.user.getId()

    def maybe_attend(self):
        """Check if we should attend"""
        if not self.userid:
            api.portal.show_message(
                _("I cannot identify you"), self.request, type="error"
            )

        attend = self.request.form.get("attend")
        if attend:
            if self.userid in self.context.attendees:
                api.portal.show_message(
                    _("It seems you are already attending this talk"),
                    self.request,
                    type="warning",
                )
            else:
                self.context.attendees += (self.userid,)
                api.portal.show_message(
                    _("Thank you for your interest!"), self.request, type="success"
                )
        else:
            if self.userid not in self.context.attendees:
                api.portal.show_message(
                    _("You were already not attending this talk"),
                    self.request,
                    type="warning",
                )
            else:
                self.context.attendees = tuple(
                    userid for userid in self.context.attendees if userid != self.userid
                )
                api.portal.show_message(
                    _("Thanks for letting us know!"), self.request, type="success"
                )

    def __call__(self):
        if self.is_posting():
            self.maybe_attend()
        return super().__call__()
