Ext.define("Portfolio.state.profile.Provider", {

	xtype: "portfolio-state-profile-provider",

	extend: "Ext.state.Provider",

	requires: [
		"Ext.Ajax",
		"Ext.state.Provider"
	],

	config: {
		cache: {}
	},

	constructor: function(o_config) {

		var i_self = this;

		i_self.initConfig(o_config);
	},

	set: function(s_key, value, f_callback) {

		var i_self = this;

		var o_cached = i_self.getCache();

		f_callback = f_callback || Ext.emptyFn;

		if (!o_cached.hasOwnProperty(s_key)) {
			o_cached[s_key] = Ext.decode(value);
		}

		Ext.Ajax.request({
			url: "/ip2-services/ip2Services.aspx",
			params: {
				func: "setProfileValue",
				key: s_key,
				value: value
			},
			method: "POST",
			success: function() {
				f_callback();
			}
		});

		i_self.getCache(o_cached);
	},

	get: function (s_key, defaultValue) {

		var i_self = this;

		var returnValue = defaultValue;

		var o_cached = i_self.getCache();

		if (o_cached.hasOwnProperty(s_key)) {
			return o_cached[s_key];
		}

		Ext.Ajax.request({
			url: "/ip2-services/ip2Services.aspx?" + Ext.Object.toQueryString({
				func: "getProfileValue",
				key: s_key
			}),
			async: false,
			success: function(i_response) {

				var o_result = Ext.decode(i_response.responseText, true) || {};
				o_cached[s_key] = o_result;

				returnValue = o_result;
			}
		});

		return returnValue;
	},

	clear: function(s_key, f_callback) {

		var i_self = this;

		var o_cached = i_self.getCache();

		f_callback = f_callback || Ext.emptyFn;

		if (!o_cached.hasOwnProperty(s_key)) {
			delete o_cached[s_key];
		}

		Ext.Ajax.request({
			url: "/ip2-services/ip2Services.aspx",
			params: {
				func: "setProfileValue",
				key: s_key,
				value: null
			},
			method: "POST",
			success: function() {
				f_callback();
			}
		});

		i_self.getCache(o_cached);
	}
});
