import requests

from helpers import response_data


class BrainTreeTokenization:

    def __init__(self, bearer_token):
        self.url = "https://payments.braintree-api.com/graphql"

        self.bearer_token = bearer_token

    def tokenize_credit_card(self):
        card = {
            "number": "",
            "cvv": "",
            "zipCode": "",
            "month": "",
            "year": "024",
        }
        credit_card_number = card['number']
        cvv = card['cvv']
        zip_code = card['zipCode']
        exp_month = card['month']
        exp_year = card['year']

        body = {
            "clientSdkMetadata": {
                "source": "client",
                "integration": "custom",
                "sessionId": "3a50bb8c-a3dc-4994-8cd3-5d2161cbe378"
            },
            "operationName": "TokenizeCreditCard",
            "query": "mutation TokenizeCreditCard($input: TokenizeCreditCardInput!) {   tokenizeCreditCard(input: $input) {     token     creditCard {       bin       brandCode       last4       expirationMonth      expirationYear      binData {         prepaid         healthcare         debit         durbinRegulated         commercial         payroll         issuingBank         countryOfIssuance         productId       }     }   } }",

            "variables": {
                "input": {"creditCard": {
                    "number": credit_card_number,
                    "expirationMonth": exp_month,
                    "expirationYear": exp_year,
                    "cvv": cvv,
                    "billingAddress": {
                        "postalCode": zip_code
                    }
                },
                    "options": {
                        "validate": True
                    }
                }
            }
        }

        """You get the Bearer data from this endpoint:
        GET on /api/customer/nonce/token
        """
        headers = {
            'Authorization': f'Bearer {self.bearer_token}',
            'Content-Type': 'application/json',
            'Braintree-Version': '2018-05-10',
            'Host': 'payments.sandbox.brain_files-api.com'

            # 'Referer':'https://www-master.staging.delivery.com'

        }
        response = requests.post(self.url, headers=headers, json=body)
        tokenize_credit_card_response = response_data.validate_response(response)

        """
        Straight from: https://graphql.braintreepayments.com/guides/making_api_calls/#understanding-responses

        Unlike a conventional REST API, GraphQL APIs do not rely on HTTP status codes to signal request outcomes. 
        Our GraphQL API always return a JSON body with the 200 status code, even when there are errors.

         """
        try:
            if "errors" not in tokenize_credit_card_response:
                tokenize_credit_card = tokenize_credit_card_response["data"]["tokenizeCreditCard"]["token"]
                # print('token in briantree payment function '+token)
                return tokenize_credit_card

            else:
                error_message = tokenize_credit_card_response['errors'][0]
                print(error_message)

        except TypeError as e:
            print("The expected data from braintree was not returned.", e)
