import { ViscaCamera, ViscaCommand } from 'visca-over-ip';
import { ActionAPI, ActionAPI_StatusTypes } from '../../ActionAPI';
import { EditorAPI, EditorAPI_Field } from '../../EditorAPI';

export function simpleCommandHandle(
	actionAPI: ActionAPI,
	command: ViscaCommand,
	properties: Properties,
	status: (text: string, type: ActionAPI_StatusTypes) => void
) {
	var connectionID = properties.connectionID != undefined ? properties.connectionID : 'none';
	if (connectionID != 'none') {
		var connection = actionAPI.getConnection('viscaOverIpCamera', connectionID);

		if (connection.instance != undefined) {
			var camera: ViscaCamera = connection.instance.camera;
			status('Sending command', 'info');

			command.on('ack', () => {
				// status('Command acknowledged', 'info');
			});
			command.on('complete', () => {
				status('Command complete', 'info');
			});
			command.on('error', (error: Error) => {
				status(`Command error: ${error.message}`, 'info');
			});
			camera.sendCommand(command);
		}
	} else status('No connection specified', 'error');
}

export function simpleCommandEditor(
	editorAPI: EditorAPI,
	properties: Properties,
	additionalFields: EditorAPI_Field[] = []
) {
	var connectionID = properties.connectionID != undefined ? properties.connectionID : 'none';
	var connectionField: EditorAPI_Field = {
		id: 'connectionID',
		name: 'Connection',
		type: 'connection',
		connectionType: 'viscaOverIpCamera',
		value: connectionID
	};

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

		var saveObject = { connectionID: fieldObject.connectionID };

		for (let i = 0; i < additionalFields.length; i++)
			saveObject[additionalFields[i].id] = fieldObject[additionalFields[i].id];

		editorAPI.saveProperties(saveObject);
	});

	editorAPI.setFields([
		connectionField,
		...additionalFields
	]);
}

interface Properties {
	connectionID: string;
}
