namespace uniflash.session {

    'use strict';
    
    export interface ISessionDataProvider {
        onSessionLoad( newData : any) : void;
        getSessionData() : any;
    }

    export class SessionDataStore {

        private sessionData: any = {};
        private sessionDataProviders: { [key:string] : ISessionDataProvider } = {};

        constructor() {
        }

        // key - to store the data based on
        // provider - {
        //		onSessionLoad, - Called when a new session is loaded; could be loaded from file or completely new
        //      getSessionData - Called before the sesison is save; so the provider could provide data	
        //	}
        registerSessionDataProvider(key:string, provider:ISessionDataProvider){

            if (this.sessionDataProviders[key])
                throw 'Session data provider ' + key + ' already exists';

            this.sessionDataProviders[key] = provider;

            // since services are lazy loaded in angular
            // the session may have been loaded without a service being yet initialized
            // thus, we call it once right away so it could initialize it self properly
            this.sendDataToProvider(key, provider);
        }

        sendDataToProvider(key:string, provider:ISessionDataProvider) {
            return provider.onSessionLoad(this.sessionData[key]);
        }

        // a different session has been loaded
        sessionLoaded() {
            _.each(this.sessionDataProviders, (provider, key) => {
                this.sendDataToProvider(key, provider);
            });
        }


        updateBeforeSave() {
           _.each(this.sessionDataProviders, (provider:ISessionDataProvider, key:string) => {
                this.sessionData[key] = provider.getSessionData();
            });
        }

        getSessionDataAll() {
            return this.sessionData;
        }

        setSessionDataAll(data:any) {
            this.sessionData = data;
        }
    }
}

