from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

from rest_framework.decorators import api_view,authentication_classes,permission_classes
from rest_framework.response import Response
from rest_framework import status

from django.utils import timezone
import datetime

from django.contrib.auth.models import User
from user_profile.models import UserProfile,CustomerProfile,ShopProfile
from payment.models import Purchase

from rest_framework.permissions import IsAuthenticated,IsAuthenticatedOrReadOnly


@csrf_exempt
@api_view(['Get'])
@permission_classes((IsAuthenticated,))
def transfer_done(request,username,format=None):

    '''
    updates the customer profile after the data transfer is done.
    '''

    '''
    if the data allowance reaches zero, remove the purchase history
    '''

    result={}
    result['message'] = 'thanks for updating us'

    return Response(result)


@csrf_exempt
@api_view(['Get'])
@permission_classes((IsAuthenticated,))
def access(request,username,format=None):

    '''
    checks if a given username has any active purchase
    and returns the result as using json
    '''

    result = {}

    try:

        user = User.objects.get(username=username)

        # check purchase validity
        result['access'] = check_user_access(user)

        # check if the user has been generated by bulk license
        # and if necessary, debit the shop account
        check_selling_shop(user)


    except User.DoesNotExist:
        result['access'] = 'forbidden'

    except Purchase.DoesNotExist:
        result['access'] = 'forbidden'

    return Response(result)


def check_selling_shop(user):

    purchases = Purchase.objects.filter(user=user)

    for purchase in purchases:
        if (purchase.selling_shop != None) &  (purchase.shop_debited == False):
            # the shop has not been debited for this license so far
            debit_shop(purchase)

def debit_shop(purchase):
    pass

        # identify which shop has sold the license

        # derive the retail fee

        # add the license used to shops's licenses

        # activate the debited flag

        # debit the amount to the shop's profile

        # send an email to the shop


def check_user_access(user):

    '''
    check if the user has at least one active purchase.
    note that the user might have multiple data plans activated.
    '''

    purchases = Purchase.objects.filter(user=user)

    for purchase in purchases:

        result = check_purchase_validity(purchase)

        if result == 'granted':
            return 'granted'

    return 'forbidden'


def check_purchase_validity(purchase):

    plan = purchase.data_transfer_plan

    if plan.plan_name in ["L1","L2","L5"]:

        if purchase.remaining_allowance_frequency > 0 :
            return 'granted'
        else:
            return 'forbidden'

    if plan.plan_name == "U1":
        period = 32
    elif plan.plan_name == "U3":
        period = 96
    elif plan.plan_name == "U6":
        period = 192

    current_time = timezone.now()
    if current_time > plan.purchase_date + datetime.timedelta(days=period):
        return 'forbidden'
    else:
        return 'granted'
