import axios from 'axios';
import { ConnectionManager_Connection } from '../../../../ConnectionManager';
import { ActionAPI } from '../../../ActionAPI';
import { EditorAPI, EditorAPI_Field } from '../../../EditorAPI';
import { Mitti } from '../MittiClass';

//TODO: Implement wrap checkbox property in editor

module.exports = (actionAPI: ActionAPI) => {
	//Handle the action when executed
	actionAPI.handle((properties: Properties, status: (text: string, type?: 'info' | 'error' | 'warn') => void) => {
		var connectionID = properties.connectionID != undefined ? properties.connectionID : 'none';
		var wrap = properties.wrap != undefined ? properties.wrap : true;
		if (connectionID != 'none') {
			var connection = actionAPI.getConnection('mitti', connectionID);
			var mitti = connection.instance as Mitti;

			mitti
				.previous(wrap)
				.then(() => {
					status(`Previous clip has been selected`, 'info');
				})
				.catch((error: Error) => {
					status(error.message, 'error');
				});
		} else status('No connection specified', 'error');
	});

	//Handle the interactive editor
	actionAPI.onOpenEditor((editorAPI: EditorAPI, properties: Properties) => {
		var connectionID = properties.connectionID != undefined ? properties.connectionID : 'none';
		var wrap = properties.wrap != undefined ? properties.wrap : true;

		editorAPI.onFieldChanges((fields: EditorAPI_Field[]) => {
			var fieldValues: Properties = <any>editorAPI.tools.objectifyFieldsValues(fields);

			editorAPI.saveProperties({ connectionID: fieldValues.connectionID, wrap: fieldValues.wrap });
		});

		editorAPI.setFields([
			{
				id: 'connectionID',
				name: 'Connection',
				type: 'connection',
				value: connectionID,
				connectionType: 'mitti'
			},
			{
				id: 'wrap',
				name: 'Wrap',
				type: 'checkbox',
				value: true
			}
		]);
	});
};

interface Properties {
	connectionID: string;
	wrap: boolean;
}
