import requests, json


class PaypingIR:
    """
        https://api.payping.ir/v3/pay
        "amount": 1000,
        "returnUrl": "https://viriakala.ir/skh-charge-wallet-successfully.php",
        "payerIdentity": "09167332792",
        "payerName": "bahman rashnu",
        "description": "text descriptioni",
        "clientRefId": "self.id"
    """
    def __init__(self, merchant_id):
        self.merchant_id = merchant_id
        self.headers = {'Content-type': 'application/json', 'Authorization': f'Bearer {merchant_id}'}

    def create_payment(self, amount, callback_url, description, order_id=None, mobile=None, email=None, currency=None, client_refid=None, **metadata):
        url = 'https://api.payping.ir/v3/pay'
        try:
            data = {}
            # data['merchant_id'] = self.merchant_id
            data['amount'] = amount
            data['returnUrl'] = callback_url
            data['description'] = description
            if order_id:
                data['order_id'] = order_id
            
            if mobile:
                data['payerIdentity'] = mobile
            
            if email:
                data['payerName'] = email

            if client_refid:
                data['clientRefId'] = str(client_refid)
            
            
            response = requests.post(url, data=json.dumps(data), headers=self.headers)
            status_code = response.status_code
            response = response.json()
            error_data = {}
            match status_code:
                case 200:
                    return response
                    
                case 400:
                    if 'metaData' in response:
                        meta_data = response['metaData']
                    else:
                        meta_data = response
                        
                    error_data['message'] = meta_data.get('errors') # ' | '.join(list(map(lambda x:x['message'], meta_data.get('errors'))))
                    error_data['code'] = meta_data.get('code')
                    error_data['payping_trace_id'] = response['paypingTraceId']
                case 500:
                    error_data['message'] = 'There was a problem with the server. Check the error code with your payment service support.'
                    error_data['code'] = 500
                case 503:
                    error_data['message'] = 'The server is currently unable to respond. Check the error code with your payment service support.'
                    error_data['code'] = 503
                case 401:
                    error_data['message'] = 'Check the API code, payment service cannot be accessed. Check the error code with your payment service support.'
                    error_data['code'] = 401
                case 403:
                    error_data['message'] = 'Unauthorized access. Check the error code with your payment service support.'
                    error_data['code'] = 403
                case 404:
                    error_data['message'] = 'The requested item is not available. Check the error code with your payment service support.'
                    error_data['code'] = 404
        except:
            pass
        return {'errors' : error_data}


    def verify_payment(self, authority, amount, payment_refid, card_number, card_hash_pan):
        '''
            authority = payment_code
            amount
            payment_refid: int
        '''
        url = 'https://api.payping.ir/v3/pay/verify'
        try:
            data = {
                "paymentRefId": payment_refid,
                "paymentCode": authority,
                "amount": amount
            }

            response = requests.post(url=url, data=json.dumps(data), headers=self.headers)
            status_code = response.status_code
            response = response.json()
            error_data = {
                'card_number': card_number,
                'card_hash_pan': card_hash_pan,
                'ref_id': payment_refid,
            }
            match status_code:
                case 200:
                    print(f'200: {response}')
                    return response
                    
                case 400 | 409:
                    if 'metaData' in response:
                        meta_data = response.get('metaData')
                    else:
                        meta_data = response
                    
                    error_data['message'] = meta_data.get('errors')
                    error_data['payping_trace_id'] = response.get('traceId')

                    if meta_data.get('code') == 110:
                        error_data['code'] = 110
                        error_data['message'] = meta_data.get('message') 

                case 500:
                    error_data['message'] = 'There was a problem with the server. Check the error code with your payment service support.'
                    error_data['code'] = 500
                case 503:
                    error_data['message'] = 'The server is currently unable to respond. Check the error code with your payment service support.'
                    error_data['code'] = 503
                case 401:
                    error_data['message'] = 'Check the API code, payment service cannot be accessed. Check the error code with your payment service support.'
                    error_data['code'] = 401
                case 403:
                    error_data['message'] = 'Unauthorized access. Check the error code with your payment service support.'
                    error_data['code'] = 403
                case 404:
                    error_data['message'] = 'The requested item is not available. Check the error code with your payment service support.'
                    error_data['code'] = 404
        except:
            pass
        return {'errors' : error_data}
