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

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

	extend: "Ext.state.Provider",

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

	set: function(s_key, value) {

        var i_provider = this;

        var n_stateIndex = Portfolio.app.getStateIndex();

        var o_states = Ext.decode(localStorage.getItem("portfolio-states"), true) || {};

        var o_state = o_states[n_stateIndex] || {};

        o_state["ext-" + s_key] = i_provider.encodeValue(value);

        o_states[n_stateIndex] = o_state;

        var s_value = JSON.stringify(o_states);

        localStorage.setItem("portfolio-states", s_value);
	},

	get: function (s_key, defaultValue) {

        var i_provider = this;

        var returnValue;

        var n_stateIndex = Portfolio.app.getStateIndex();

        var o_states = Ext.decode(localStorage.getItem("portfolio-states"), true) || {};

        var o_state = o_states[n_stateIndex] || {};

        if (n_stateIndex === 0) {

            var s_stored = localStorage.getItem("ext-" + s_key);

            var decoded = i_provider.decodeValue(s_stored);

            if(decoded) {

                o_state["ext-" + s_key] = decoded;

                o_states[n_stateIndex] = o_state;

                var s_value = JSON.stringify(o_states);

                localStorage.setItem("portfolio-states", s_value);

                localStorage.removeItem("ext-" + s_key);

                returnValue = decoded;
            }
        }

        if (!returnValue) {
            returnValue = i_provider.decodeValue(o_state["ext-" + s_key]);
        }

        return returnValue || defaultValue;
	},

	clear: function(s_key) {

        var n_stateIndex = Portfolio.app.getStateIndex();

        var o_states = Ext.decode(localStorage.getItem("portfolio-states"), true) || {};

        var o_state = o_states[n_stateIndex] || {};

        delete o_state["ext-" + s_key];

        o_states[n_stateIndex] = o_state;

        var s_value = JSON.stringify(o_states);

        localStorage.setItem("portfolio-states", s_value);

        var s_stored = localStorage.getItem("ext-" + s_key);

        if (s_stored) {
            localStorage.removeItem("ext-" + s_key);
        }
	}
});
