import datetime
import stripe

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

from payments.payments.recursive_searcher import get_recursively

OLD_SUB = None
HOW_MUCH_MONEY = None


@api_view(['POST'])
def create_sub(request):
    # here we retrieve the customer made in create_customer_and_payment_method
    # for creating a sub
    customer_id = [x for x in stripe.Customer.list(limit=3)["data"]
                   if x["description"] == "Test Customer"][0]["id"]

    # here we retrieve a product id for retrieving a price id
    product_id = [x for x in stripe.Product.list(limit=2)["data"]
                  if x["name"] == "Silver Advance"][0]["id"]
    price_id = [x for x in stripe.Price.list(limit=2000)["data"]
                if x["product"] == product_id][0]["id"]

    # here we create the sub based on customer and price ids
    subscription = stripe.Subscription.create(
        customer=customer_id,
        items=[
            {"price": price_id},
        ],
    )

    return Response(status=status.HTTP_204_NO_CONTENT, data=subscription)


@api_view(['POST'])
def cancel_subscription(request):
    try:
        # here we hardcode retrieve a subscription
        sub = stripe.Subscription.retrieve(
            stripe.Subscription.list(limit=1, status="active")
            ["data"][0]["id"],
        )
        remove_sub = stripe.Subscription.delete(
            sub,
        )
        return Response(status=status.HTTP_204_NO_CONTENT, data=remove_sub)
    except Exception as e:
        print(e)
        remove_sub = {}
        return Response(status=status.HTTP_404_NOT_FOUND, data=remove_sub)


@api_view(['GET'])
def subscription_list(request):
    """
        STATUSES:
        active
        past_due
        unpaid
        canceled
        xc
        incomplete_expired
        trialing
        all
        ended
        Here we can check for example unpaid subs or incomplete due to
        3d secure security.
    """
    return Response(status=status.HTTP_200_OK,
                    data=stripe.Subscription.list(limit=300, status="active",
                                                  customer="cus_KwBZaypcmQkq7w"))


@api_view(['POST'])
def subscription_alteration(request):
    global OLD_SUB, HOW_MUCH_MONEY
    """
        In this function we calculate how much money we need for refunding,
        we cancel the sub, refund the customer, activate a new subscription.
    """

    customer_id = [x for x in stripe.Customer.list(limit=3)["data"]
                   if x["description"] == "Test Customer"][0]["id"]

    charge = stripe.Charge.list(limit=10)["data"][6] if \
        stripe.Charge.list(limit=5)["data"][0]["customer"] \
        == customer_id else None

    if datetime.datetime.now().day in [x for x in range(1, 6)]:
        HOW_MUCH_MONEY = int(charge["amount"] * 1)
    elif datetime.datetime.now().day in [x for x in range(6, 11)]:
        HOW_MUCH_MONEY = int(charge["amount"] * 0.5)
    else:
        HOW_MUCH_MONEY = 0

    # here we cancel the old sub and the last invoice generated by the system
    old_product = [x for x in stripe.Product.list(limit=10)["data"]
                   if x["name"] == "Silver Advance"][0]["id"]
    for sub in stripe.Subscription.list(limit=10)["data"]:
        if old_product in get_recursively(sub, "product"):
            OLD_SUB = sub
            break
    delete_sub = stripe.Subscription.delete(
        OLD_SUB["id"],
    )

    # we can only refund a customer if sum is greater then 1
    if HOW_MUCH_MONEY > 1:
        refund = stripe.Refund.create(
            charge=charge["id"],
            amount=HOW_MUCH_MONEY,
            reason="requested_by_customer"
        )

    # here we retrieve a product id for retrieving a price id
    product_id = [x for x in stripe.Product.list(limit=2)["data"]
                  if x["name"] == "Gold Special"][0]["id"]
    price_id = [x for x in stripe.Price.list(limit=2000)["data"]
                if x["product"] == product_id][0]["id"]

    subscription = stripe.Subscription.create(
        customer=customer_id,
        items=[
            {"price": price_id},
        ],
    )

    return Response(status=status.HTTP_204_NO_CONTENT, data=subscription)
