﻿TNRIS.ASPProfileStateProvider = function(config) {
    Ext.apply(this, config, {
        stateProfileProperty: 'mapState'
    });
    
    TNRIS.ASPProfileStateProvider.superclass.constructor.call(this,config);
    this.addEvents({'load': true});
    
    this.state = this.readProfile();
    this.stateLoaded = false;
    // only save the state to the server every 5 seconds
    this.on('statechange', this.saveProfile, this, {buffer : 5000});
    this.addEvents({'statesaved':true});
};

Ext.extend(TNRIS.ASPProfileStateProvider, Ext.state.Provider,
    /** @scope TNRIS.ASPProfileStateProvider */
    {
    readProfile: function() {
        state = {};
        Sys.Services.ProfileService.load(null, this.onProfileLoaded.bind(this), function(a) {throw "Unable to load previous applicationState from the server " + a; });
        return state;
    },
    
    saveProfile: function() {
        Sys.Services.ProfileService.properties[this.stateProfileProperty] = this.encodeValue(this.state);
        Sys.Services.ProfileService.save(null, function() { this.fireEvent('statesaved'); }.bind(this), function(a) { throw "Unable to save the application state to the server: " + a; });
    },
    
    onProfileLoaded: function(a) {
        var values = Sys.Services.ProfileService.properties[this.stateProfileProperty];
        if (values != null && values.length > 0) {
            this.state = this.decodeValue(values);
        }
        
        // notify listeners the profile is available
        this.fireEvent('load');
    }
});

if (typeof(Sys) !== "undefined") { Sys.Application.notifyScriptLoaded(); }
