from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.models import User
from rest_framework.permissions import IsAuthenticated
from django.shortcuts import get_object_or_404
from core.models import UserInformation, Course, UserCourse, CoursePayment, PromoCode
from .serializers import PromoCodeSerializer

# Create your views here.

class PromoCodeList(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user

        user_information = user.userinformation
        
        if user_information.role != 'Admin':
            return Response({'error': 'Unauthorized access.'}, status=status.HTTP_401_UNAUTHORIZED)

        promocode_count = PromoCode.objects.all().count()

        offset = request.GET.get('offset', 0)
        limit = request.GET.get('limit', promocode_count+1)

        try:
            offset = int(offset)
            limit = int(limit)
        except:
            return Response({'error': 'Offset and limit must be integer numbers.'}, status=status.HTTP_400_BAD_REQUEST)

        promocode = PromoCode.objects.all().order_by('-id')[offset:limit]

        serializer = PromoCodeSerializer(promocode, many=True)

        return Response({'promocode_data': serializer.data, 'promocode_count': promocode_count}, status=status.HTTP_200_OK)

    
    def post(self, request):
        user = request.user

        user_information = user.userinformation
        
        if user_information.role != 'Admin':
            return Response({'error': 'Unauthorized access.'}, status=status.HTTP_401_UNAUTHORIZED)
        
        code = request.data.get('code', '')
        discount_amount = request.data.get('discount_amount', '')
        discount_type = request.data.get('discount_type', '')
        valid_from = request.data.get('valid_from', '')
        valid_to = request.data.get('valid_to', '')
        total_count = request.data.get('total_count', '')
        code_status = request.data.get('code_status', '')
        
        if discount_amount == '' or discount_type == '' or code == '' or valid_from == '' or valid_to == '' or total_count == '' or code_status == '':
            return Response({'error': 'Data not found.'}, status=status.HTTP_404_NOT_FOUND)
        
        if PromoCode.objects.filter(code=code).exists():
            return Response({'error': 'This promocode already exists.'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            discount_amount = float(discount_amount)
        except:
            return Response({'error': 'Total token count must be a number.'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            total_count = int(total_count)
        except:
            return Response({'error': 'Total token count must be an integer.'}, status=status.HTTP_400_BAD_REQUEST)

        promo_code = PromoCode.objects.create(
            code=code,
            discount_amount=discount_amount,
            discount_type=discount_type,
            valid_from=valid_from,
            valid_to=valid_to,
            total_count=total_count,
            taken_count=0,
            code_status=code_status
        )

        return Response(status=status.HTTP_200_OK)


class PromoCodeDetails(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        user = request.user

        user_information = user.userinformation
        
        if user_information.role != 'Admin':
            return Response({'error': 'Unauthorized access.'}, status=status.HTTP_401_UNAUTHORIZED)
            
        code_id = request.GET.get('code_id', '')

        if code_id == '':
            return Response({'error': 'Promo Code id not found.'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            code_id = int(code_id)
        except:
            return Response({'error': 'Invalid promo code id.'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            promo_code = PromoCode.objects.get(id=code_id)
        except PromoCode.DoesNotExist:
            return Response({'error': 'Promocode not found.'}, status=status.HTTP_404_NOT_FOUND)

        serializer = PromoCodeSerializer(promo_code)

        return Response({'promocode_data': serializer.data}, status=status.HTTP_200_OK)



    def put(self, request):
        user = request.user

        user_information = user.userinformation
        
        if user_information.role != 'Admin':
            return Response({'error': 'Unauthorized access.'}, status=status.HTTP_401_UNAUTHORIZED)

        id = request.data.get('id', '')
        code = request.data.get('code', '')
        discount_amount = request.data.get('discount_amount', '')
        discount_type = request.data.get('discount_type', '')
        valid_from = request.data.get('valid_from', '')
        valid_to = request.data.get('valid_to', '')
        total_count = request.data.get('total_count', '')
        code_status = request.data.get('code_status', '')

        if id == '' or discount_amount == '' or discount_type == '' or code == '' or valid_from == '' or valid_to == '' or total_count == '' or code_status == '':
            return Response({'error': 'Data not found.'}, status=status.HTTP_404_NOT_FOUND)
        

        check_code = PromoCode.objects.filter(code=code)
        if check_code.count() > 0:
            if check_code[0].id != id:
                return Response({'error': 'This promocode already exists.'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            promo_code = PromoCode.objects.get(id=id)
        except PromoCode.DoesNotExist:
            return Response({'error': 'Promocode not found.'}, status=status.HTTP_404_NOT_FOUND)

        promo_code.code = code
        promo_code.discount_amount = discount_amount
        promo_code.discount_type = discount_type
        promo_code.valid_from = valid_from
        promo_code.valid_to = valid_to
        promo_code.total_count = total_count
        promo_code.code_status = code_status

        promo_code.save()

        return Response({'success': 'Promocode updated.'}, status=status.HTTP_200_OK)


    def delete(self, request):
        user = request.user

        user_information = user.userinformation
        
        if user_information.role != 'Admin':
            return Response({'error': 'Unauthorized access.'}, status=status.HTTP_401_UNAUTHORIZED)        

        id = request.data.get('id', '')

        if id == '':
            return Response({'error': 'Promocode id not found.'}, status=status.HTTP_404_NOT_FOUND)

        try:
            id = int(id)
        except:
            return Response({'error': 'Id must be an integer'}, status=status.HTTP_400_BAD_REQUEST)

        try:
            promo_code = PromoCode.objects.get(id=id)
        except PromoCode.DoesNotExist:
            return Response({'error': 'Promocode not found.'}, status=status.HTTP_404_NOT_FOUND)

        promo_code.delete()

        return Response({'error': 'Promocode deleted.'}, status=status.HTTP_200_OK)