import json

import requests
from requests_pkcs12 import get,post
pkcs12_filename = 'dvldigitalprojects.p12'
pkcs12_password = 'QNlhRStcY7mB'


def get_domain_url():
    return 'https://sandboxapi.paymtech.kz/'

def get_kwargs_for_request():
    return {
        'headers': {
            'content-type': 'application/json',
        },
        'auth': ('dvldigitalprojects', 'aPqSRVZhxFjjSqbB'),
        'pkcs12_filename': pkcs12_filename,
        'pkcs12_password': pkcs12_password
    }

def ping():

    url = f'{get_domain_url()}ping'
    data = {}

    try:
        msg = f'GET {url}'
        print(msg)
        res = get(
            url,
            **get_kwargs_for_request()
        )

        msg = f'answer received = {str(res)}'
        print(msg)
    except Exception as e:
        msg = f'Exception GET {url} = {str(e)} ({str(res)})'
        print(msg)
        res = None
        return False

    return True


def get_order_status(bank_order_id):

    url = f'{get_domain_url()}orders/{str(bank_order_id)}'

    res = None

    data = {
        'expand': [
            'card', 'client', 'location', 'custom_fields',
            'issuer', 'secure3d', 'operations', 'cashflow'
        ]
    }

    try:
        msg = f'GET {url}'
        print(msg)
        res = get(
            url,
            data=json.dumps(data),
            **get_kwargs_for_request()
        )

        msg = f'get_order_status answer received = {str(res)}'
        print(msg)
    except Exception as e:
        msg = f'Exception get_order_status GET {url} = {str(e)} ({str(res)})'
        print(msg)
        res = None

    return res


def create_order(data):

    url = f'{get_domain_url()}orders/create'

    res = None

    try:
        msg = f'POST {url}'
        print(msg)
        res = post(
            url,
            data=json.dumps(data),
            **get_kwargs_for_request()
        )

        msg = f'create_order answer received = {str(res)}'
        print(msg)
    except Exception as e:
        msg = f'Exception create_order POST {url} = {str(e)} ({str(res)})'
        print(msg)
        res = None

    return res