
/*
	KyteAPI.js

	KyteAPI is the main interface with Kyte.
	RequestManager and RESTRequest process all Kyte requests made by the API.

	Developed by Eneko Alonso
	ealonso@level-studios.com
	Copyright 2009 LEVEL Studios

*/

var KyteAPI = new Class({
	Implements: [Options, Events],

	options: {
		gid: 0,
		playerSettings: {
			width: "100%",
			height: "100%",
			p: "781",
			// preShowAction: 'none',
			postShowAction: 'none',
			ignoreNewShows: false,
			disableShowNavigation: true,
			hideShowsTab: true,
			hideProduceTab: true,
			premium: false,
			producerMode: 'always'
		}
	},

	initialize: function(options) {
		this.setOptions(options);
		this.ready = false;
		this.getKeys();
	},

	getKeys: function() {
		if (!Liferay || !KyteStatus.enabled) return;
		Liferay.Service.KYTE.Kyte.getKyteKeys({
			groupId: this.options.gid,
			userId: themeDisplay.getUserId()
		}, function(data) {
			console.log('Kyte data:');
			if (console.dir) console.dir(data);
			this.data = data;
			this.authenticateByLogin();
		}.bind(this));
		setTimeout(function(){this.getKeys.call(this)}.bind(this), 300000); // Regenerate keys every 5 minutes
	},

	authenticateByLogin: function() {
		if (!Liferay || !KyteStatus.enabled) return;
		if (themeDisplay && themeDisplay.isSignedIn() && this.data.currentUser) {
			var user = this.data.currentUser.l;
			var acct = 'community';
		} else {
			var user = KyteStatus.anonymous
			var acct = 'main';
		};
		this.request({
			account:    acct,
			handler:    'userService',
			command:    'authenticateByLogin',
			parameters: '&ln=' + user,
			onComplete: function(request, data) {
				this.ticket = data.result;
				this.ready = true;
				this.fireEvent('kyteReady');
			}.bind(this)
		});
	},

	request: function(options) {
		if (!Liferay || !KyteStatus.enabled) return;
		new RESTRequest($extend(options, {
			ak: this.data.accounts[options.account||KyteStatus.mainAccount].ak,
			as: this.data.accounts[options.account||KyteStatus.mainAccount].as
		}));
	}
});

/*
	RequestManager (Global Object)
	Queues REST requests and processes them sequentially
*/
var RequestManager = {
	requests: [],
	requestInProgress: false,
	currentRequest: 0,

	newRequest: function(request) {
		this.requests.push(request);
		return this.requests.length-1;
	},

	processQueue: function() {
		if (this.requestInProgress) return;

		if (this.currentRequest < this.requests.length) {
			this.requests[this.currentRequest++].execute();
			this.requestInProgress = true;
		}
	},

	requestComplete: function(request) {
		this.requestInProgress = false;
		this.processQueue();
	}
};

/*
	RESTRequest
	Encapsulates a single REST request
*/
var RESTRequest = new Class({
	Implements: [Options, Events],

	serverURI: 'http://' + KyteStatus.server + '/services/rest/',
	failed:    false,
	result:    null,

	options: {
		account: 'main',
		handler: '',
		command: '',
		parameters: ''
	},

	initialize: function(options) {
		this.setOptions(options);
		this.index = RequestManager.newRequest(this);
		RequestManager.processQueue();
	},

	execute: function() {
		this.asset = new Asset.javascript(
			this.serverURI + this.options.handler + '.' + this.options.command +
			'?ak=' + this.options.ak + '&as=' + this.options.as + this.options.parameters +
			'&callback=RequestManager.requests[' + this.index + '].callback'
		);
	},

	callback: function(data) {
		console.log('Kyte request callback: ', this.asset.src);
		if (console.dir) console.dir(data);

		if (data.error) {
			this.failed = true;
			this.result = data.error;
			console.warn("Request:", this.asset.get('src'));
			console.error("Error:", data.error.message);
		} else {
			this.result = data.result;
			this.fireEvent('complete', [this, data]);
		}

		this.asset.destroy();
		RequestManager.requestComplete(this);
	}
});
