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

export var ZoomOSC_Basic = {
	handleAction(oscAction: string) {
		return (ActionAPI: ActionAPI) => {
			ActionAPI.onExecute((properties, status, deck) =>
				ZoomOSC_Basic.onExecute(ActionAPI, oscAction, properties, status, deck)
			);
			ActionAPI.onOpenEditor(ZoomOSC_Basic.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}/${properties.target}/${oscAction}`, properties.targetValue as any, () => {
					status(`OSC Action ${oscAction} has been called with ${properties.targetValue}`, '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 target = properties.target != undefined ? properties.target : 'userName';
		var targetValue = properties.targetValue != undefined ? properties.targetValue : '';

		var connectionField: EditorAPI_Field = {
			id: 'connectionID',
			name: 'Connection',
			type: 'connection',
			connectionType: 'zoomosc',
			value: connectionID
		};
		var targetField: EditorAPI_Field = {
			id: 'target',
			name: 'Target',
			type: 'select',
			value: target,
			values: [
				{ id: 'userName', text: 'By username' },
				{ id: 'targetID', text: 'By target id' },
				{ id: 'zoomID', text: 'By Zoom id' },
				{ id: 'galIndex', text: 'By gallery index' },
				{ id: 'me', text: 'Me' },
				{ id: 'all', text: 'All' }
			]
		};
		var targetValueField: EditorAPI_Field = {
			id: 'targetValue',
			name: 'Value',
			type: 'text',
			value: targetValue
		};

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

interface Properties {
	connectionID: string;
	target: 'userName' | 'targetID' | 'zoomID' | 'galIndex' | 'me';
	targetValue: string;
}
