goog.provide('oneup.Application');

goog.require('oneup.DataAccess');

oneup.Application = function() {
	this.setReady(['achievements', 'userdata'], false);
	this.achievements = {};
	this.achievementGroups = {};
	this.started = false;
	this.uiManager = new oneup.UiManager();
	this.dataAccess = new oneup.DataAccess();
	this.userData = new oneup.UserData();
	goog.events.listen(this.userData, 'user changed', this.userDataChanged, null, this);
	// load it into the app
	this.setupAchievements();
	
};
goog.inherits(oneup.Application, goog.events.EventTarget);

oneup.Application.prototype.setupAchievements = function(init) {
	var that = this;
	this.dataAccess.getAllAchievements(function(e) {
		var data = e.target.getResponseJson();
		for (var i = 0; i < data.length; i++) {
			var tmpAch = new oneup.Achievement(data[i]);
			that.achievements[data[i].id] = tmpAch;
			that.achievementGroups[data[i].group] = that.achievementGroups[data[i].group] || [];
			that.achievementGroups[data[i].group].push(tmpAch);
		}
		that.setReady('achievements');
	});
}

oneup.Application.prototype.setReady = function(ids, opt_readyStatus) {
	var readyStatus = true;
	if (opt_readyStatus != null) {
		readyStatus = opt_readyStatus;
	}
	
	if (!this.readyStates) {
		this.readyStates = {};
	}
	if (goog.isArray(ids)) {
		for (var i = 0; i < ids.length; i++) {
			this.readyStates[ids[i]] = readyStatus;
		}
	} else {
		this.readyStates[ids] = readyStatus;
	}
	//check if ready phase
	if (readyStatus && !this.started) {
		var states = objectToArray(this.readyStates, true);
		for (var i = 0; i < states.length; i++) {
			if (!states[i]) {
				return;
			}
		}
		this.started = true;
		//start ui here;
		hideLoading();
		this.refresh();
	}
}

oneup.Application.prototype.refresh = function() {
	if (this.started) {
		this.uiManager.refresh();
	}
}

oneup.Application.prototype.userDataChanged = function(e) {
	if (this.started) {
		this.refresh();
	} else {
		this.setReady('userdata');
	} 
}

oneup.Application.prototype.getAchievements = function(ids) {
	var res = [];
	for (var i = 0; i < ids.length; i++) {
		if (this.achievements[ids[i]]) {
			res.push(this.achievements[ids[i]]);
		}
	}
	return res;
}

