angular.module('app', [
    'ui.router',
    'ui.bootstrap',
    'angular-confirm',
    'ngStorage',
    'angularSpinner',
    'FBAngular',
    
    'sqevents',
    'sqplugin',
    // App
    'app.layout',
    'app.login'

]) 
.config(function ($provide, $httpProvider, SQEventsProvider, $compileProvider) {
    $compileProvider.debugInfoEnabled(false);
    $httpProvider.useApplyAsync(true);
    
    // Intercept http calls.
    $provide.factory('ErrorHttpInterceptor', function ($q, $injector) {
        var errorCounter = 0;

        function notifyError(rejection){
            console.error(rejection.status + ' - ' + rejection.statusText);
        }

        return {
            // On request failure
            requestError: function (rejection) {
                // show notification
                notifyError(rejection);
                // Return the promise rejection.
                return $q.reject(rejection);
            },

            // On response failure
            responseError: function (rejection) {
                // show notification
                notifyError(rejection);
                
                if(rejection.status === 401) {
                    if(rejection.data.disabled != undefined){
                        $injector.get('LoginService').setDisabled(rejection.data.disabled);
                    }
                    $injector.get('$state').transitionTo('sqlogin');
                }
                // Return the promise rejection.
                return $q.reject(rejection);
            }
        };
    });

    // Add the interceptor to the $httpProvider.
    $httpProvider.interceptors.push('ErrorHttpInterceptor');

})
.constant('APP_CONFIG', window.appConfig)
.run(function ($rootScope, $state, $stateParams, LoginService) {
    console.log("app started");
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams;
    
    $rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
        console.log("Going from "+fromState.name+" to "+toState.name);
        
        var isLogin = toState.name === "sqlogin";
        if(isLogin){
            return; // no need to redirect 
        }
        
        // redirect if not authenticated
        LoginService.checkRemoteAccess().then(function(result){
            if(!result.data.success){
                if(result.data.disabled != undefined){
                    LoginService.setDisabled(result.data.disabled);
                }
                e.preventDefault(); // stop current execution
                $state.go('sqlogin', {redirectTo: toState.name}); // go to login
            }
        });
        
    });
});