import axios from 'axios';
import { ActionAPI } from '../../../ActionAPI';
import { EditorAPI, EditorAPI_Field } from '../../../EditorAPI';

module.exports = (actionAPI: ActionAPI) => {
	actionAPI.handle((properties: Properties, status) => {
		var connectionID =
			properties.connectionID != undefined && properties.connectionID.length > 0
				? properties.connectionID
				: 'none';

		if (connectionID != 'none') {
			var connection = actionAPI.getConnection('powerpoint-bridge', connectionID);

			axios
				.get(`http://${connection.properties.ip}:${connection.properties.port}/v1/next`)
				.then(() => {
					status('Action completed');
				})
				.catch(() => {
					status('Unable to reach Powerpoint-Bridge');
				});
		} else status('No connection specified', 'error');
	});

	actionAPI.onOpenEditor((editorAPI: EditorAPI, properties: Properties) => {
		var connectionID =
			properties.connectionID != undefined && properties.connectionID.length > 0
				? properties.connectionID
				: 'none';
		var connectionField: EditorAPI_Field = {
			id: 'connectionID',
			name: 'connection',
			type: 'connection',
			connectionType: 'powerpoint-bridge',
			value: connectionID
		};
		editorAPI.onFieldChanges((fields) => {
			var values = editorAPI.tools.objectifyFieldsValues(fields);
			editorAPI.saveProperties({ connectionID: values.connectionID });
		});
		editorAPI.setFields([
			connectionField
		]);
	});
};

interface Properties {
	connectionID: string;
}
