from logging import getLogger
from plone import api
from ploneintranet import api as pi_api
from ploneintranet.core import _
from ploneintranet.notifications.mails.base import BaseEmail
from warnings import warn

logger = getLogger(__name__)


class AggregatedEmailView(BaseEmail):
    show_preferences_link = True

    @property
    def apps(self):
        return [None] + pi_api.apps.get_apps()

    @property
    def mail_main_template(self):
        """Getting this like here/email-notification-template will not work because
        the context is not traversable
        """
        return api.content.get_view(
            "email-notification-template", self.context, self.request
        )

    @property
    def actor_ids(self):
        return {
            notification.logged_event.actor_id
            for notification in self.context.notifications
        }

    @property
    def translatable_subject(self):
        if len(self.context.notifications) == 1:
            message = self.context.notifications[0].short_message
            if message:
                return message

        proto = api.content.get_view("proto", self.context, self.request)
        actor_ids = list(self.actor_ids)
        if len(actor_ids) == 1:
            return _(
                "subject_mini_digest_mail_1",
                default=(
                    "A quick update about what ${actor1} is doing on ${site_title}"
                ),
                mapping={
                    "site_title": proto.site_title,
                    "actor1": self.userprofiles.get_fullname_for(actor_ids[0]),
                },
            )
        if len(actor_ids) == 2:
            return _(
                "subject_mini_digest_mail_2",
                default="${actor1} and ${actor2} are working on ${site_title}",
                mapping={
                    "site_title": proto.site_title,
                    "actor1": self.userprofiles.get_fullname_for(actor_ids[0]),
                    "actor2": self.userprofiles.get_fullname_for(actor_ids[1]),
                },
            )
        return _(
            "subject_mini_digest_mail_3",
            default="${actor1} and others are working on ${site_title}",
            mapping={
                "site_title": proto.site_title,
                "actor1": self.userprofiles.get_fullname_for(actor_ids[0]),
            },
        )

    @property
    def recipient_user(self):
        """This is normally a ploneintranet.userprofile object"""
        return pi_api.userprofile.get(self.context.recipient_id)

    def send_email(self):
        if not api.portal.get_registry_record(
            "ploneintranet.notifications.email.enabled", default=True
        ):
            warn("Email notifications are disabled.")
            return
        if len(self.context.notifications) == 0:
            logger.info("No valid notifications to send.")
            return
        if not self.recipient:
            logger.info("Ignoring invalid user %s.", self.context.recipient_id)
            return
        if (
            api.content.get_state(self.recipient_user)
            not in self._userprofile_active_states
        ):
            logger.info("Skipping deactivated user %s.", self.context.recipient_id)
            return
        return super().send_email()


class DigestEmailView(AggregatedEmailView):
    show_header = True

    @property
    def translatable_subject(self):
        proto = api.content.get_view("proto", self.context, self.request)
        return _(
            "subject_digest_mail",
            default="Here's an update of what happened on ${site_title}",
            mapping={"site_title": proto.site_title},
        )
