namespace uniflash.session {
    'use strict';

    angular.module('uniflash').run(['$rootScope', '$state', 'ufSession',
        ($rootScope: angular.IRootScopeService, 
         $state : angular.ui.IStateService,
         ufSession : uniflash.session.SessionService ) => {
            let confirmed = false;
            $rootScope.$on('$stateChangeStart',
                (event: angular.IAngularEvent, toState: angular.ui.IState, toParams, fromState: angular.ui.IState) => {
                    // if we are leaving the main page to go back to the welcome page
                    if (toState.name === "welcome" && _.startsWith(fromState.name, "main") && !confirmed  ) {
                        event.preventDefault();
                        ufSession.confirmLeave()
                        .then( () => {
                             // state change will trigger another stateChangeStart
                             // there for we need to set a flag saying we have already confirmed
                             confirmed = true;
                             $state.go(toState.name).finally(() => {
                                 confirmed = false;
                             });
                        });
                    }
                }
            );
        }
    ]);

}