import stripe
import json
from functions.Response import API_Error 

def create_checkout_session(params):
    priceId = params.get('priceId')
    hostname = params.get('hostname')
    try:
        checkout_session = stripe.checkout.Session.create(
            line_items=[
                {
                    'price': priceId,
                    'quantity': 1,
                },
            ],
            mode='subscription',
            success_url= hostname+
            '/plans?success=true&session_id={CHECKOUT_SESSION_ID}',
            cancel_url=hostname + '/plans?canceled=true',
        )
        return checkout_session.url
    except Exception as e:
        print(e)
        raise API_Error("Failed to create checkout session.", 500, meta=dict(error=e))


def webhook_received(request):
    # Replace this endpoint secret with your endpoint's unique secret
    # If you are testing with the CLI, find the secret by running 'stripe listen'
    # If you are using an endpoint defined with the API or dashboard, look in your webhook settings
    # at https://dashboard.stripe.com/webhooks
    webhook_secret = 'whsec_12345'
    request_data = json.loads(request.data)

    if webhook_secret:
        # Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
        signature = request.headers.get('stripe-signature')
        try:
            event = stripe.Webhook.construct_event(
                payload=request.data, sig_header=signature, secret=webhook_secret)
            data = event['data']
        except Exception as e:
            return e
        # Get the type of webhook event sent - used to check the status of PaymentIntents.
        event_type = event['type']
    else:
        data = request_data['data']
        event_type = request_data['type']
    data_object = data['object']

    print('event ' + event_type)

    if event_type == 'checkout.session.completed':
        print('🔔 Payment succeeded!')
    elif event_type == 'customer.subscription.trial_will_end':
        print('Subscription trial will end')
    elif event_type == 'customer.subscription.created':
        print('Subscription created %s', event.id)
    elif event_type == 'customer.subscription.updated':
        print('Subscription created %s', event.id)
    elif event_type == 'customer.subscription.deleted':
        # handle subscription canceled automatically based
        # upon your subscription settings. Or if the user cancels it.
        print('Subscription canceled: %s', event.id)

    return {'status': 'success'}