(function () {
    'use strict';

    angular
        .module('app', ['angular-growl', 'ngTable', 'ui.router', 'ngMessages', 'ngStorage', 'ngRoute', 'ngAnimate', 'ui.bootstrap', 'ngCookies'])
        .config(config)
        .run(run);

    function config($stateProvider, $urlRouterProvider, growlProvider) {
        
        growlProvider.globalTimeToLive(4000);
        growlProvider.globalPosition('top-right');
        // default route
        $urlRouterProvider.otherwise("/login");

        // app routes
        $stateProvider
            .state('home', {
                url: '/home',
                templateUrl: 'home/app.view.html',
                controller: 'Home.AppViewController',
                controllerAs: 'vm',
            })
            .state('user', {
                url: '/',
                templateUrl: 'home/user.view.html',
                controller: 'Home.UserViewController',
                controllerAs: 'vm'
            })
            .state('login', {
                url: '/login',
                templateUrl: 'login/index.view.html',
                controller: 'Login.IndexController',
                controllerAs: 'vm',
            });
    }

    function run($rootScope, $http, $location, $localStorage, $cookies) {
        // keep user logged in after page refresh
        $rootScope.globals = $cookies.getObject('dashboard_session') || {};
        if ($rootScope.globals.currentUser) {
            $http.defaults.headers.common['Authorization'] = 'Bearer ' + $rootScope.globals.currentUser.authdata; // jshint ignore:line
        }

        $rootScope.$on('$locationChangeStart', function (event, next, current) {
            // redirect to login page if not logged in
            if (!$rootScope.globals.currentUser) {
                $location.path('/login');
            }
            else {
                $location.path('/');
            }
        });
    }
})();