import { EditorAPI, EditorAPI_Field } from '../../../EditorAPI';
import { Client } from 'node-osc';
import { ActionAPI } from '../../../ActionAPI';

export var ZoomOSC_ConnectionOnly = {
	handleAction(oscAction: string) {
		return (ActionAPI: ActionAPI) => {
			ActionAPI.onExecute((properties, status, deck) =>
				ZoomOSC_ConnectionOnly.onExecute(ActionAPI, oscAction, properties, status, deck)
			);
			ActionAPI.onOpenEditor(ZoomOSC_ConnectionOnly.onOpenEditor);
		};
	},

	onExecute(ActionAPI: ActionAPI, oscAction: string, properties: Properties, status, deck) {
		if (properties.connectionID != undefined && properties.connectionID.length > 0) {
			var connection = ActionAPI.getConnection('zoomosc', properties.connectionID);
			if (connection) {
				var ip: string = connection.properties.ip;
				var port: number = connection.properties.port;
				var header: number = connection.properties.header;

				var client = new Client(ip, port);
				client.send(`/${header}/${oscAction}`, <any>[], () => {
					status(`OSC Action ${oscAction} has been called`, 'info');
					client.close();
				});
			} else status('Connection does not exist', 'error');
		} else status('No connectionID specified', 'error');
	},

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

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

		EditorAPI.onFieldChanges((fields) => {
			var fieldObject = EditorAPI.tools.objectifyFieldsValues(fields);
			EditorAPI.saveProperties({
				connectionID: fieldObject.connectionID,
				target: fieldObject.target,
				targetValue: fieldObject.targetValue
			});
		});
		EditorAPI.setFields([
			connectionField
		]);
	}
};

interface Properties {
	connectionID: string;
}
