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

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

		var state = properties.state != undefined && properties.state.length > 0 ? properties.state : 'offline';

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

			if (connection && connection.instance) {
				connection.instance
					.setRecording(state == 'on')
					.then(() => status(`Recording state has been set to ${state}`))
					.catch((error) => status(error, 'error'));
			}
		} else status('No connection specfied', 'error');
	});

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

		var connectionField: EditorAPI_Field = {
			id: 'connectionID',
			name: 'Connection',
			value: connectionID,
			type: 'connection',
			connectionType: 'wirecast-bridge'
		};
		var stateField: EditorAPI_Field = {
			id: 'state',
			name: 'State',
			type: 'select',
			value: state,
			values: []
		};

		if (connectionID != 'none')
			stateField.values = [
				{ id: 'on', text: 'On' },
				{ id: 'off', text: 'Off' }
			];
		EditorAPI.setFields([
			connectionField,
			stateField
		]);

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

			connectionField.value = fieldObject.connectionID;
			stateField.value = fieldObject.state;

			if (connectionID != fieldObject.connectionID) {
				connectionID = fieldObject.connectionID;

				stateField.values =
					connectionID != 'none'
						? [
								{ id: 'on', text: 'On' },
								{ id: 'off', text: 'Off' }
							]
						: [];

				EditorAPI.setFields([
					connectionField,
					stateField
				]);
			}
			EditorAPI.saveProperties({ connectionID: fieldObject.connectionID, state: fieldObject.state });
		});
	});
};

interface Properties {
	connectionID: string;
	state: 'on' | 'off';
}
