import { ActionAPI } from '../../ActionAPI';
import { EditorAPI, EditorAPI_Field } from '../../EditorAPI';
import { IntegrationAPI } from '../../IntegrationApi';
const axios = require('axios').default;

module.exports = (api: IntegrationAPI) => {
	//Register a action
	api.registerAction('request', (actionAPI: ActionAPI) => {
		//Handle the action when executed
		actionAPI.handle(
			(properties: Request_Properties, status: (text: string, type?: 'info' | 'error' | 'warn') => void) => {
				axios
					[properties.method](properties.address)
					.then((response) => {
						status('Request has been delivered.');
					})
					.catch((error) => {
						status('Unable to deliver request.', 'error');
					});
			}
		);

		//Handle the interactive editor
		actionAPI.onOpenEditor((editorAPI: EditorAPI, properties: Request_Properties) => {
			var method: Request_Properties_Methods = properties.method != undefined ? properties.method : 'get';
			var address: string = properties.address != undefined ? properties.address : '';

			editorAPI.onFieldChanges((fields: EditorAPI_Field[]) => {
				var fieldValues = editorAPI.tools.objectifyFieldsValues(fields);
				editorAPI.saveProperties({ method: fieldValues.method, address: fieldValues.address });
			});

			editorAPI.setFields([
				{
					id: 'method',
					name: 'Method',
					type: 'select',
					value: method,
					values: [
						{ id: 'get', text: 'GET' },
						{ id: 'post', text: 'POST' },
						{ id: 'put', text: 'PUT' }
					]
				},
				{
					id: 'address',
					name: 'Address',
					type: 'text',
					value: address
				}
			]);
		});
	});
};

interface Request_Properties {
	method: Request_Properties_Methods;
	address: string;
}

type Request_Properties_Methods = 'post' | 'get' | 'put';
