from logging import getLogger
from plone.memoize.view import memoize
from plone.registry.interfaces import IRegistry
from ploneintranet import api as pi_api
from ploneintranet.admintool.interfaces import IStripeSettings
from Products.Five import BrowserView
from zExceptions import NotFound
from zope.component import getUtility
from zope.interface import implementer
from zope.publisher.interfaces import IPublishTraverse

import stripe

logger = getLogger(__name__)


@implementer(IPublishTraverse)
class StripeCheckout(BrowserView):
    """Redirect a user to the stripe checkout payment form."""

    is_modal_panel = True

    def publishTraverse(self, request, name):
        self.user = pi_api.userprofile.get(name)
        if not self.user:
            raise NotFound("Cannot find user profile %r" % name)
        return self

    @property
    @memoize
    def stripe_settings(self):
        registry = getUtility(IRegistry)
        return registry.forInterface(IStripeSettings)

    @property
    def public_key(self):
        settings = self.stripe_settings
        if settings.mode == "live":
            return settings.live_publishable_key
        else:
            return settings.test_publishable_key

    @property
    def secret_key(self):
        settings = self.stripe_settings
        if settings.mode == "live":
            return settings.live_secret_key
        else:
            return settings.test_secret_key

    @property
    def product_id(self):
        settings = self.stripe_settings
        if settings.mode == "live":
            return settings.live_product_id
        else:
            return settings.test_product_id

    @property
    @memoize
    def stripe_session(self):
        try:
            self.user
        except AttributeError:
            raise NotFound("No user profile specified")

        stripe.api_key = self.secret_key
        base_url = self.context.absolute_url()
        session = stripe.checkout.Session.create(
            client_reference_id=self.user.UID(),
            customer_email=self.user.email,
            payment_method_types=["card"],
            mode="subscription",
            subscription_data={"items": [{"plan": self.product_id}]},
            success_url=f"{base_url}/@@stripe-success",
            cancel_url=f"{base_url}/@@stripe-cancel",
        )
        return session
