angular.module('app.program', [])
.factory('serviceProgram', function(socket) {

	if(LOGPRESSO.shared.isServiceProgramLoaded && angular.isUndefined(location._testPort_)) {
		console.log('child serviceProgram init')
		return LOGPRESSO.shared.serviceProgram;
	}

	console.log('serviceProgram init')
	LOGPRESSO.shared.isServiceProgramLoaded = true;

	var events = {};

	function getAvailablePrograms() {
		return socket.send('org.araqne.dom.msgbus.ProgramPlugin.getAvailablePrograms', {}, 0);
	}

	function addEventListener(pack, app, eventName, fn) {
		var s = events[pack + '\\' + app] = {};
		s[eventName] = fn;
		console.log(events)
	}

	function dispatchEvent(pack, app, eventName) {
		var s = events[pack + '\\' + app];
		if(!!s) {
			if(angular.isFunction(s[eventName])) {
				events[pack + '\\' + app][eventName]();
			}
		}

	}

	var fns = {
		getAvailablePrograms: getAvailablePrograms,
		addEventListener: addEventListener,
		dispatchEvent: dispatchEvent
	}

	LOGPRESSO.shared.serviceProgram = fns;
	return fns;
});