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

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

		if (connectionID != 'none') {
			var connection = actionAPI.getConnection('protor', connectionID);

			if (connection && connection.instance != undefined) {
				var protor: Protor = connection.instance;

				protor.fadeIn(duration)
			} else status('Connection not online', 'error');
		} else status('No connection specified', 'error');
	});

	actionAPI.onOpenEditor((editorAPI: EditorAPI, properties: Properties) => {
		var connectionID =
			properties.connectionID != undefined
				? properties.connectionID
				: 'none';
		var duration =
			properties.duration != undefined
				? properties.duration
				: 0;

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

		var durationField: EditorAPI_Field = {
			id: 'duration',
			name: 'Duration',
			type: 'number',
			value: duration
		};

		editorAPI.setFields([connectionField, durationField])

		editorAPI.onFieldChanges((fields) => {
			var fieldObject = editorAPI.tools.objectifyFieldsValues(fields)
			editorAPI.saveProperties({ connectionID: fieldObject.connectionID, duration: fieldObject.duration })
		})

	});
};

interface Properties {
	connectionID: string;
	duration: number;
}
