import { ConnectionValidatorAPI, IntegrationAPI } from '../../IntegrationApi';
import { Mitti } from './MittiClass';
const axios = require('axios').default;

module.exports = (api: IntegrationAPI) => {
	//Register a action
	api.registerAction('clip', require('./actions/clip'));
	api.registerAction('play', require('./actions/play'));
	api.registerAction('stop', require('./actions/stop'));
	api.registerAction('next', require('./actions/next'));
	api.registerAction('previous', require('./actions/previous'));

	api.registerConnectionValidator('mitti', (ValidatorAPI: ConnectionValidatorAPI) => {
		var properties = ValidatorAPI.properties;
		if (properties.ip != undefined) {
			if (ValidatorAPI.instance != undefined && (ValidatorAPI.instance as Mitti).connected == true)
				return ValidatorAPI.callback(true);

			var mitti = new Mitti(properties.ip);
			var canRespond = true;
			var timeout: NodeJS.Timeout = setTimeout(() => {
				canRespond = false;
				ValidatorAPI.callback(false, 'Timeout while trying to connect to Mitti');
			}, 3000);
			mitti.on('connected', () => {
				if (canRespond == true) {
					canRespond = false;
					ValidatorAPI.setInstance(mitti);
					clearTimeout(timeout);
					ValidatorAPI.callback(true);
				}
			});
			mitti.on('connecterror', (errorMessage: string) => {
				if (canRespond == true) {
					canRespond = false;
					clearTimeout(timeout);
					ValidatorAPI.callback(false, errorMessage);
				}
			});
		} else ValidatorAPI.callback(false, 'Incorrect ip address syntax');
	});
};

interface Mitti_Properties {
	ip: string;
}
