picard.controller('BaseCtrl', ['$rootScope', '$scope', '$location', '$routeParams', 'Auth', function ($rootScope, $scope, $location, $routeParams, Auth) {
    $rootScope.$on('loginRequired', function () {
        if ($rootScope.auth.Authenticated) {
            $location.path('/');
        } else {
            var came_from = $routeParams.came_from;
            if (typeof came_from === 'undefined' && $location.path() !== '/Login') {
                came_from = $location.path();
            }
            $location.path('/Login').search({came_from: came_from});
        }
    });

    $rootScope.$on('notification', function (event, data) {
        if (data.Message !== '') {
            var msg = angular.isArray(data.Message) ? data.Message : JSON.parse(data.Message);
            if (angular.isArray(msg)) {
                data.Header = msg[0];
                data.Message = msg[1];
            } else if (angular.isObject(msg)) {
                data.Header = msg.Header;
                data.Message = msg.Message;
            } else {
                data.Header = '';
                data.Message = msg;
            }
        }
        $scope.toasts.push(data);
    });

    $scope.toasts = [];
    $scope.clearToast = function (item) {
        var idx = $scope.toasts.indexOf(item);
        if (idx !== -1) {
            $scope.toasts.splice(idx, 1);
        }
    };

    $rootScope.$on("$routeChangeStart", function (event, next, current) {
        Auth.get(function (u, putResponseHeaders) {
            $rootScope.auth = u;
            $rootScope.perms = u.Permissions;
        });
    });
}]);

