goog.provide('oneup.UserData');

goog.require('goog.dom');

oneup.UserData = function() {
	this.achieved = {};
	FB.init({appId: goog.dom.getElement('fbAppId').value, status: true, cookie: true, xfbml: true});
	var that = this;
	FB.Event.subscribe('auth.sessionChange', function(response) {that.updateUserData();});
	this.updateUserData();
}
goog.inherits(oneup.UserData, goog.events.EventTarget);

oneup.UserData.prototype.updateUserData = function() {
	var that = this;
	goog.dom.$('fbLoginState').innerHTML = '';
	FB.api('/me', function(response) {
		that.fbData = response;
		if (!that.fbData.error) {
		  goog.dom.$('fbLoginState').innerHTML = '';
		  goog.dom.$('fbLoginButton').style.display = 'none';
		  var fbLoginState = goog.dom.$('fbLoginState')
		  fbLoginState.innerHTML = '';
		  fbLoginState.style.display = '';
		  var profileName = goog.dom.createDom('span', {'class':'profileName'}, that.fbData.name);
		  var profilePic = goog.dom.createDom('img', {'src': 'http://graph.facebook.com/'+that.fbData.id+'/picture', 'class': 'profilePic'});
		  fbLoginState.appendChild(profileName);
		  fbLoginState.appendChild(profilePic);
		  
		  oneup.app.dataAccess.isAdmin(function(response) {
		    var isAdmin = response.target.getResponseJson().value;
		    if (isAdmin == "true") {
		      fbLoginState.appendChild(goog.dom.createDom('a', {'href':'#admin'}, 'Admin'));
		    }
		  });
		}
		else {
		  goog.dom.$('fbLoginButton').style.display = '';
		  var fbLoginState = goog.dom.$('fbLoginState')
		  fbLoginState.style.display = 'none';
		}
		that.loadUserPrefs();
	});
}

oneup.UserData.prototype.isLoggedIn = function() {
	return !!(this.fbData && !this.fbData.error);
}

oneup.UserData.prototype.loadUserPrefs = function() {
	var that = this;
	that.achieved = {};
	if (this.isLoggedIn()) {
		//do ajax
		oneup.app.dataAccess.getMyAchievements(function(response) {
			var json = response.target.getResponseJson();
			for (var i = 0; i < json.length; i++) {
				that.achieved[json[i].achievement] = true;
			}
			//fire event
			goog.events.dispatchEvent(that, 'user changed'); 
		});
	} else {
		//fire event
		goog.events.dispatchEvent(that, 'user changed');
	}
}

oneup.UserData.prototype.hasAchievement = function(id) {
	return !!this.achieved[id];
}

oneup.UserData.prototype.setAchieved = function(id, bool) {
	this.achieved[id] = bool;
}

