# coding: utf-8

"""
    OAuth2 API

    OAuth2 Token Service (OAuth2)

    OpenAPI spec version: v3
    
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""


from __future__ import absolute_import

import sys
import os
import re

# python 2 and python 3 compatibility library
from six import iteritems

from ..configuration import Configuration
from ..api_client import ApiClient
import CyberSource.logging.log_factory as LogFactory


class OAuthApi(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    Ref: https://github.com/swagger-api/swagger-codegen
    """
	
    def __init__(self, merchant_config, api_client=None):
        config = Configuration()
        if api_client:
            self.api_client = api_client
        else:
            if not config.api_client:
                config.api_client = ApiClient()
            self.api_client = config.api_client
        self.api_client.set_configuration(merchant_config) 
        self.logger = LogFactory.setup_logger(self.__class__.__name__, self.api_client.mconfig.log_config)


    def create_access_token(self, create_access_token_request, **kwargs):
        """
        Create access token and refresh token
        This request is used by technology partners to obtain an access token and a refresh token, which are contained in the response.  The partner can then use the access token for authentication when submitting API requests to CyberSource on behalf of the merchant.   The request must include the authorization code that was included in the URL redirect response from CyberSource (see [full documentation](https://developer.cybersource.com/api/developer-guides/OAuth/cybs_extend_intro.html)). Access tokens expire after 15 minutes. The refresh token is used to create a new access token, it expires after one year. 
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.create_access_token(create_access_token_request, callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param CreateAccessTokenRequest create_access_token_request: Request payload (required)
        :param str v_c_client_correlation_id: We recommended that you submit this header with a unique value in every client request to this endpoint.  It is sent back in the response header and logged both in the request log and response log. 
        :return: AccessTokenResponse
                 If the method is called asynchronously,
                 returns the request thread.
        """

        if self.api_client.mconfig.log_config.enable_log:
            self.logger.info("CALL TO METHOD `create_access_token` STARTED")
        
        kwargs['_return_http_data_only'] = True
        if kwargs.get('callback'):
            return self.create_access_token_with_http_info(create_access_token_request, **kwargs)
        else:
            (data) = self.create_access_token_with_http_info(create_access_token_request, **kwargs)
            return data

    def create_access_token_with_http_info(self, create_access_token_request, **kwargs):
        """
        Create access token and refresh token
        This request is used by technology partners to obtain an access token and a refresh token, which are contained in the response.  The partner can then use the access token for authentication when submitting API requests to CyberSource on behalf of the merchant.   The request must include the authorization code that was included in the URL redirect response from CyberSource (see [full documentation](https://developer.cybersource.com/api/developer-guides/OAuth/cybs_extend_intro.html)). Access tokens expire after 15 minutes. The refresh token is used to create a new access token, it expires after one year. 
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please define a `callback` function
        to be invoked when receiving the response.
        >>> def callback_function(response):
        >>>     pprint(response)
        >>>
        >>> thread = api.create_access_token_with_http_info(create_access_token_request, callback=callback_function)

        :param callback function: The callback function
            for asynchronous request. (optional)
        :param CreateAccessTokenRequest create_access_token_request: Request payload (required)
        :param str v_c_client_correlation_id: We recommended that you submit this header with a unique value in every client request to this endpoint.  It is sent back in the response header and logged both in the request log and response log. 
        :return: AccessTokenResponse
                 If the method is called asynchronously,
                 returns the request thread.
        """

        all_params = ['create_access_token_request', 'v_c_client_correlation_id']
        all_params.append('callback')
        all_params.append('_return_http_data_only')
        all_params.append('_preload_content')
        all_params.append('_request_timeout')

        params = locals()
        for key, val in iteritems(params['kwargs']):
            if key not in all_params:
                raise TypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method create_access_token" % key
                )
            params[key] = val
        del params['kwargs']
        # verify the required parameter 'create_access_token_request' is set
        if ('create_access_token_request' not in params) or (params['create_access_token_request'] is None):
            if self.api_client.mconfig.log_config.enable_log:
                self.logger.error("InvalidArgumentException : Missing the required parameter `create_access_token_request` when calling `create_access_token`")            
            raise ValueError("Missing the required parameter `create_access_token_request` when calling `create_access_token`")

        if 'v_c_client_correlation_id' in params and len(params['v_c_client_correlation_id']) > 36:
            if self.api_client.mconfig.log_config.enable_log:
                self.logger.error("InvalidArgumentException : Invalid value for parameter `v_c_client_correlation_id` when calling `create_access_token`, length must be less than or equal to `36`")
            raise ValueError("Invalid value for parameter `v_c_client_correlation_id` when calling `create_access_token`, length must be less than or equal to `36`")
        if 'v_c_client_correlation_id' in params and len(params['v_c_client_correlation_id']) < 36:
            if self.api_client.mconfig.log_config.enable_log:
                self.logger.error("InvalidArgumentException : Invalid value for parameter `v_c_client_correlation_id` when calling `create_access_token`, length must be greater than or equal to `36`")
            raise ValueError("Invalid value for parameter `v_c_client_correlation_id` when calling `create_access_token`, length must be greater than or equal to `36`")
        if 'v_c_client_correlation_id' in params and not re.search('^[A-Za-z0-9\\.\\-_:]+$', params['v_c_client_correlation_id']):
            if self.api_client.mconfig.log_config.enable_log:
                self.logger.error("InvalidArgumentException : Invalid value for parameter `v_c_client_correlation_id` when calling `create_access_token`, must conform to the pattern `/^[A-Za-z0-9\\.\\-_:]+$/`")
            raise ValueError("Invalid value for parameter `v_c_client_correlation_id` when calling `create_access_token`, must conform to the pattern `/^[A-Za-z0-9\\.\\-_:]+$/`")

        collection_formats = {}

        path_params = {}

        query_params = []

        header_params = {}
        if 'v_c_client_correlation_id' in params:
            header_params['v-c-client-correlation-id'] = params['v_c_client_correlation_id']

        form_params = []
        local_var_files = {}

        body_params = None
        if 'create_access_token_request' in params:
            body_params = params['create_access_token_request']
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.\
            select_header_accept(['application/json;charset=utf-8'])

        # HTTP header `Content-Type`
        header_params['Content-Type'] = self.api_client.\
            select_header_content_type(['application/x-www-form-urlencoded'])

        # Authentication setting
        auth_settings = []

        return self.api_client.call_api(f'/oauth2/v3/token', 'POST',
                                        path_params,
                                        query_params,
                                        header_params,
                                        body=body_params,
                                        post_params=form_params,
                                        files=local_var_files,
                                        response_type='AccessTokenResponse',
                                        auth_settings=auth_settings,
                                        callback=params.get('callback'),
                                        _return_http_data_only=params.get('_return_http_data_only'),
                                        _preload_content=params.get('_preload_content', True),
                                        _request_timeout=params.get('_request_timeout'),
                                        collection_formats=collection_formats)
