/**
 * BoldSign API
 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
 *
 * The version of the OpenAPI document: 1
 * 
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';

import {
    ObjectSerializer, Authentication, VoidAuth, Interceptor,
    HttpBasicAuth, HttpBearerAuth, ApiKeyAuth, OAuth, RequestFile, 
    BillingViewModel,ErrorResult,
} from '../model';

import {
    HttpError,
    optionsI,
    returnTypeT,
    returnTypeI,
    generateFormData,
    toFormData,
    queryParamsSerializer,
    USER_AGENT,
} from './';

let defaultBasePath = 'https://api.boldsign.com';

// ===============================================
// This file is autogenerated - Please do not edit
// ===============================================


export class PlanApi {
    protected _basePath = defaultBasePath;
    protected _defaultHeaders : any = { 'User-Agent': USER_AGENT };
    protected _useQuerystring : boolean = false;

    protected authentications = {
        'default': <Authentication>new VoidAuth(),
        'Bearer': new ApiKeyAuth('header', 'Authorization'),
        'X-API-KEY': new ApiKeyAuth('header', 'X-API-KEY'),
    }

    protected interceptors: Interceptor[] = [];

    constructor(basePath?: string) {
        if (basePath) {
            this.basePath = basePath;
        }
    }

    set useQuerystring(value: boolean) {
        this._useQuerystring = value;
    }

    set basePath(basePath: string) {
        this._basePath = basePath;
    }

    set defaultHeaders(defaultHeaders: any) {
        this._defaultHeaders = { ...defaultHeaders, "User-Agent": USER_AGENT };
    }

    get defaultHeaders() {
        return this._defaultHeaders;
    }

    get basePath() {
        return this._basePath;
    }

    public setDefaultAuthentication(auth: Authentication) {
        this.authentications.default = auth;
    }

    public setApiKey(apikey: string) {
        this.authentications["X-API-KEY"].apiKey = apikey;
    }

    public setAccessToken(accessToken: string) {
        this.authentications["Bearer"].apiKey = 'bearer ' + accessToken;
    }

    public addInterceptor(interceptor: Interceptor) {
        this.interceptors.push(interceptor);
    }

    /**
     * 
     * @summary Gets the Api credits details.
     * @param options
     */
    public async apiCreditsCount (options: optionsI = {headers: {}}) : Promise<returnTypeT<BillingViewModel>> {
        const localVarPath = this.basePath + '/v1/plan/apiCreditsCount';
        let localVarQueryParameters: any = {};
        let localVarHeaderParams: any = (<any>Object).assign({}, this._defaultHeaders);
        const produces = ['application/json'];
        // give precedence to 'application/json'
        if (produces.indexOf('application/json') >= 0) {
            localVarHeaderParams['content-type'] = 'application/json';
        } else {
            localVarHeaderParams['content-type'] = produces.join(',');
        }
        let localVarFormParams: any = {};
        let localVarBodyParams: any = undefined;

        (<any>Object).assign(localVarHeaderParams, options.headers);

        let localVarUseFormData = false;

        let data = {};
        if (localVarUseFormData) {
          const formData = toFormData(localVarFormParams);
          data = formData;
          localVarHeaderParams = {
            ...localVarHeaderParams,
            ...formData.getHeaders(),
          };
        }

        let localVarRequestOptions: AxiosRequestConfig = {
            method: 'GET',
            params: localVarQueryParameters,
            headers: localVarHeaderParams,
            url: localVarPath,
            paramsSerializer: this._useQuerystring ? queryParamsSerializer : undefined,
            maxContentLength: Infinity,
            maxBodyLength: Infinity,
            responseType: "json",
        };

        if (localVarRequestOptions.method !== 'GET') {
           localVarRequestOptions.data = data;
        }
        let authenticationPromise = Promise.resolve();

        if (this.authentications["X-API-KEY"].apiKey) {
            authenticationPromise = authenticationPromise.then(() => this.authentications["X-API-KEY"].applyToRequest(localVarRequestOptions));
        }
        if (this.authentications["Bearer"].apiKey) {
            authenticationPromise = authenticationPromise.then(() => this.authentications["Bearer"].applyToRequest(localVarRequestOptions));
        }
        authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions));

        let interceptorPromise = authenticationPromise;
        for (const interceptor of this.interceptors) {
            interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions));
        }

        return interceptorPromise.then(() => {
            return new Promise<returnTypeT<BillingViewModel>>((resolve, reject) => {
                axios.request(localVarRequestOptions)
                    .then((response) => {
                        handleSuccessfulResponse<BillingViewModel>(
                          resolve,
                          reject,
                          response,
                          "BillingViewModel",
                        );
                    }, (error: AxiosError) => {
                        if (error.response == null) {
                            reject(error);
                            return;
                        }

                        if (handleErrorCodeResponse(
                            reject,
                            error.response,
                            200,
                            "BillingViewModel",
                        )) {
                          return;
                        }
                        if (handleErrorCodeResponse(
                            reject,
                            error.response,
                            401,
                            "ErrorResult",
                        )) {
                          return;
                        }


                        reject(error);
                    });
            });
        });
    }
}

function deserializeIfNeeded<T> (obj: T, classname: string): T {
  if (obj !== null && obj !== undefined && obj.constructor.name !== classname) {
    return ObjectSerializer.deserialize(obj, classname);
  }

  return obj;
}

type AxiosResolve<T> = (
  value: (returnTypeT<T> | PromiseLike<returnTypeT<T>>),
) => void

type AxiosReject = (reason?: any) => void;

function handleSuccessfulResponse<T>(
  resolve: AxiosResolve<T>,
  reject: AxiosReject,
  response: AxiosResponse,
  returnType?: string,
) {
    let body = response.data;

    if (
        response.status &&
        response.status >= 200 &&
        response.status <= 299
    ) {
        if (returnType) {
            body = ObjectSerializer.deserialize(body, returnType);
        }

        resolve({ response: response, body: body });
    } else {
        reject(new HttpError(response, body, response.status));
    }
}

function handleErrorCodeResponse(
  reject: AxiosReject,
  response: AxiosResponse,
  code: number,
  returnType: string
): boolean {
    if (response.status !== code) {
        return false;
    }

    const body = ObjectSerializer.deserialize(
        response.data,
        returnType,
    );

    reject(new HttpError(response, body, response.status));

    return true;
}

function handleErrorRangeResponse(
  reject: AxiosReject,
  response: AxiosResponse,
  code: string,
  returnType: string
): boolean {
    let rangeCodeLeft = Number(code[0] + "00");
    let rangeCodeRight = Number(code[0] + "99");

    if (response.status >= rangeCodeLeft && response.status <= rangeCodeRight) {
        const body = ObjectSerializer.deserialize(
            response.data,
            returnType,
        );

      reject(new HttpError(response, body, response.status));

      return true;
    }

    return false;
}
