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 speed = properties.speed != undefined && properties.speed.length > 0 ? properties.speed : 'offline';

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

			if (connection && connection.instance) {
				connection.instance
					.setTransitionSpeed(speed)
					.then(() => status(`Transition speed has been set to ${speed}`))
					.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 speed = properties.speed != undefined && properties.speed.length > 0 ? properties.speed : 'offline';

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

		if (connectionID != 'none')
			speedField.values = [
				{ id: 'slowest', text: 'Slowest' },
				{ id: 'slow', text: 'Slow' },
				{ id: 'normal', text: 'Normal' },
				{ id: 'faster', text: 'Faster' },
				{ id: 'fastest', text: 'Fastest' }
			];
		EditorAPI.setFields([
			connectionField,
			speedField
		]);

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

			connectionField.value = fieldObject.connectionID;
			speedField.value = fieldObject.speed;

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

				speedField.values =
					connectionID != 'none'
						? [
								{ id: 'slowest', text: 'Slowest' },
								{ id: 'slow', text: 'Slow' },
								{ id: 'normal', text: 'Normal' },
								{ id: 'faster', text: 'Faster' },
								{ id: 'fastest', text: 'Fastest' }
							]
						: [];

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

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