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 : 'none';

		if (connectionID != 'none' && connectionID.length > 0) {
			var connection = ActionAPI.getConnection('wirecast-bridge', connectionID);
			if (connection && connection.instance) {
				connection.instance
					.go()
					.then(() => {
						status('Go!', 'info');
					})
					.catch((error) => {
						status(error, 'error');
					});
			}
		} else status('No connection specified', 'error');
	});

	ActionAPI.onOpenEditor((EditorAPI: EditorAPI, properties: Properties) => {
		var connectionID = properties.connectionID != undefined ? properties.connectionID : 'none';

		var connectionField: EditorAPI_Field = {
			id: 'connectionID',
			name: 'Connection',
			type: 'connection',
			connectionType: 'wirecast-bridge',
			value: connectionID
		};

		EditorAPI.onFieldChanges((fields) => {
			var fieldObject = EditorAPI.tools.objectifyFieldsValues(fields);

			EditorAPI.saveProperties({ connectionID: fieldObject.connectionID });
		});

		EditorAPI.setFields([
			connectionField
		]);
	});
};

interface Properties {
	connectionID: string;
}
