import {
	OptionsWithUri,
} from 'request';

import {
	IExecuteFunctions,
	ILoadOptionsFunctions,
} from 'n8n-core';

import {
	IDataObject, NodeApiError
} from 'n8n-workflow';

// Rest API for generating access token
async function plutioApiRequestToken(this: IExecuteFunctions | ILoadOptionsFunctions): Promise<any> { // tslint:disable-line:no-any
	const credentials = await this.getCredentials('plutioApi');
	const clientId = `${credentials.clientId}`;
	const clientSecret = `${credentials.clientSecret}`;
	const business = `${credentials.business}`;
	const endpoint = 'api.plutio.com/v1.10';
	const returnData: IDataObject[] = [];

	let responseData;

	const options: OptionsWithUri = {
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded',
			'business': business,
		},
		method: 'POST',
		body: {
			'client_id': clientId,
			'client_secret': clientSecret,
			'grant_type': 'client_credentials',
		},
		uri: `https://${endpoint}/oauth/token`,
		json: true,
	};
	try {
		responseData = await this.helpers.request!(options);
		if (Array.isArray(responseData)) {
			returnData.push.apply(returnData, responseData as IDataObject[]);
		} else {
			if (responseData === undefined) {
				responseData = {
					success: true,
				};
			}
			returnData.push(responseData as IDataObject);
		}
		if (returnData[0].accessToken) {
			return returnData[0].accessToken;
		}
	} catch (error) {
		throw new NodeApiError(this.getNode(), error);
	}
}

// Rest API function for plutio node.
export async function plutioApiRequest(this: IExecuteFunctions | ILoadOptionsFunctions, method: string, resource: string, body: any = {}, query: IDataObject = {}, uri?: string, option: IDataObject = {}): Promise<any> { // tslint:disable-line:no-any
	const endpoint = 'api.plutio.com/v1.10';
	const credentials = await this.getCredentials('plutioApi');
	const plutioApiToken = await plutioApiRequestToken.call(this);
	const business = `${credentials.business}`;

	let options: OptionsWithUri = {
		headers: {
			'Content-Type': 'application/json',
			'Authorization': `Bearer ${Buffer.from(plutioApiToken).toString()}`,
			'Business': business,
		},
		method,
		body,
		qs: query,
		uri: uri || `https://${endpoint}${resource}`,
		json: true,
	};
	if (!Object.keys(body).length) {
		delete options.body;
	}
	if (!Object.keys(query).length) {
		delete options.qs;
	}
	options = Object.assign({}, options, option);
	try {
		return await this.helpers.request!(options);
	} catch (error) {
		throw new NodeApiError(this.getNode(), error);
	}
}

export function capitalize(s: string): string {
	if (typeof s !== 'string') return '';
	return s.charAt(0).toUpperCase() + s.slice(1);
}