from plone import api
from plone.memoize.view import memoize
from ploneintranet.admintool.browser.interfaces import IGeneratePWResetToken
from Products.Five import BrowserView


class UserCreatedMail(BrowserView):
    """An email sent when the user has been created"""

    def is_pending(self):
        """Check if the user state is pending"""
        return api.content.get_state(self.context) == "pending"

    @property
    @memoize
    def reset_data(self):
        """Request a password reset"""
        ppr = api.portal.get_tool("portal_password_reset")
        if not IGeneratePWResetToken.providedBy(self.request):
            return {"randomstring": "exampletoken", "expires": ppr.expirationDate()}
        return ppr.requestReset(self.context.username)

    @property
    @memoize
    def random_string(self):
        """Obtain a random string for resetting the password"""
        if not self.reset_data:
            return ""
        return self.reset_data["randomstring"]

    @property
    @memoize
    def password_reset_link(self):
        """Generate the password reset link"""
        return api.content.get_view(
            "mail_password_template", self.context, self.request
        ).construct_url(self.random_string, userid=self.context.username)

    @property
    @memoize
    def expiration_date(self):
        if not self.reset_data:
            return ""
        return api.portal.get_localized_time(self.reset_data["expires"])

    @property
    @memoize
    def footer(self):
        footer = api.portal.get_registry_record(
            "plonenintranet.admintool.mail_user_created_footer", default=None
        )
        if not footer:
            return None
        footer = footer.replace("\n", "<br />")
        pt = api.portal.get_tool("portal_transforms")
        footer = pt.convert("safe_html", footer)
        return footer
