import axios from 'axios';
import { ConnectionManager_Connection } from '../../../../ConnectionManager';
import { ActionAPI } from '../../../ActionAPI';
import { EditorAPI, EditorAPI_Field } from '../../../EditorAPI';
import { Mitti } from '../MittiClass';

module.exports = (actionAPI: ActionAPI) => {
	//Handle the action when executed
	actionAPI.handle((properties: Properties, status: (text: string, type?: 'info' | 'error' | 'warn') => void) => {
		var connectionID = properties.connectionID != undefined ? properties.connectionID : 'none';
		if (connectionID != 'none') {
			var connection = actionAPI.getConnection('mitti', connectionID);
			var mitti = connection.instance as Mitti;

			mitti
				.stop()
				.then(() => {
					status(`Current clip stopped`, 'info');
				})
				.catch((error: Error) => {
					status(error.message, 'error');
				});
		} else status('No connection specified', 'error');
	});

	//Handle the interactive editor
	actionAPI.onOpenEditor((editorAPI: EditorAPI, properties: Properties) => {
		var connectionID = properties.connectionID != undefined ? properties.connectionID : 'none';

		editorAPI.onFieldChanges((fields: EditorAPI_Field[]) => {
			var fieldValues: Properties = <any>editorAPI.tools.objectifyFieldsValues(fields);

			editorAPI.saveProperties({ connectionID: fieldValues.connectionID });
		});

		editorAPI.setFields([
			{
				id: 'connectionID',
				name: 'Connection',
				type: 'connection',
				value: connectionID,
				connectionType: 'mitti'
			}
		]);
	});
};

interface Properties {
	connectionID: string;
}
