from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND
from django.contrib.auth import get_user_model
from ..services import create_payment, verify_payment
from ..serializers import PaymentSerializer
UserGet = get_user_model()



class PaymentCreate(APIView):
    permission_classes = (AllowAny, )
    serializer_class = PaymentSerializer
    model = serializer_class.Meta.model
    
    def post(self, request):
        '''
        order_id        str
        amount          float
        description     str
        callback_url    str
        mobile          str
        email           str
        currency        str
        '''

        try:
            # assert 'order_id' in self.request.data, 'order_id is required.'
            assert 'amount' in self.request.data, 'amount is required.'
            # assert 'description' in self.request.data, 'description is required.'

            data = {
                # 'order_id': self.request.data['order_id'],
                'amount': self.request.data['amount'],
                'description': 'django-chelseru: new order',
                'mobile': '',
                'email': '',
            }

            if self.request.user.mobile_drf_chelseru.mobile:
                data['mobile'] = self.request.user.mobile_drf_chelseru.mobile
            
            if self.request.user.email:
                data['email'] = self.request.user.email
            
            obj = self.model.objects.create(user=request.user, amount=data['amount'], description=data['description'], mobile=data['mobile'], email=data['email'])
            data['client_refid'] = obj.user.id
            
            if 'callback_url' in request.data:
                data['callback_url'] = request.data['callback_url']
                obj.callback_url = data['callback_url']

            if 'order_id' in self.request.data:
                data['order_id'] = self.request.data['order_id']
                obj.order_id = data['order_id']
            
            if 'description' in self.request.data:
                data['description'] = self.request.data['description']
                obj.description = data['description']

            if 'mobile' in self.request.data:
                data['mobile'] = self.request.data['mobile']
                obj.mobile = data['mobile']

            if 'email' in self.request.data:
                data['email'] = self.request.data['email']
                obj.email = data['email']

            if 'currency' in self.request.data:
                data['currency'] = self.request.data['currency']
                obj.currency = data['currency']
            
            obj.save()
            response = create_payment(**data)
            obj.set_request_data(**response)

            return Response({'details': response}, status=HTTP_200_OK)
        except AssertionError as e:
            return Response({'error': str(e)}, status=HTTP_400_BAD_REQUEST)


class PaymentCallback(APIView):
    permission_classes = (AllowAny, )
    serializer_class = PaymentSerializer
    model = serializer_class.Meta.model
    
    def get(self, request):
        '''
        query params:
            Authority
            Status (OK, NOK)
        '''
        authority = request.GET.get('Authority')
        status = request.GET.get('Status')

        if status  and authority:
            # and status == 'OK'
            try:
                obj = self.model.objects.get(authority=authority)
                response = verify_payment(authority=authority, amount=obj.amount)
                if response is None:
                    return Response({'error': 'callback data is none, please check your gateway settings.'}, status=HTTP_400_BAD_REQUEST)
                
                obj.set_verify_data(**response)
                return Response({'details': response}, status=HTTP_200_OK)
            except self.model.DoesNotExist:
                return Response({'error': 'payment not found.'}, status=HTTP_404_NOT_FOUND)

        return Response({'error': 'The transaction was unsuccessful or canceled.'}, status=HTTP_400_BAD_REQUEST)
    
    def post(self, request):
        # print(request.data)
        if 'paymentCode' in request.data:
            authority = request.POST.get('paymentCode')
        else:
            authority = request.POST.get('authority')

        if 'paymentRefId' in request.data:
            payment_refid = request.POST.get('paymentRefId')
        else:
            payment_refid = None
        
        if 'gatewayAmount' in request.data:
            gateway_amount = request.POST.get('gatewayAmount')

        if 'cardNumber' in request.data:
            card_number = request.POST.get('cardNumber')
        else:
            card_number = None
        
        if 'cardHashPan' in request.data:
            card_hash_pan = request.POST.get('cardHashPan')
        else:
            card_hash_pan = None

        try:
            obj = self.model.objects.get(authority=authority)
            response = verify_payment(authority=authority, amount=obj.amount, payment_refid=payment_refid, card_number=card_number, card_hash_pan=card_hash_pan)
            
            if response is None:
                return Response({'error': 'callback data is none, please check your gateway settings.'}, status=HTTP_400_BAD_REQUEST)
            
            obj.set_verify_data(**response)
            return Response({'details': response}, status=HTTP_200_OK)
        
        except self.model.DoesNotExist:
            return Response({'error': 'payment not found.'}, status=HTTP_404_NOT_FOUND)
        return Response({})
