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

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

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

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

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

interface ZoomProperties {
	connectionID: string;
}
