'use strict';
angular.module('MailApp',
    [
        'ui.bootstrap',
        'core',
        'ui.router',
        'ngCookies',
        //'ngMockE2E',
        'alert',
        'loading',
        'login',
        'messages',
        'ncy-angular-breadcrumb'
    ])
    
    .run(function ($transitions, Auth) {

        $transitions.onStart({to: ["messages", "messages.*", "tables", "dashboard"]}, function (trans) {
            var $state = trans.router.stateService;
            // If the user is not authenticated
            if (!Auth.isAuthorized()) {
                return $state.target("login");
            }
        });
    })

    .controller('MasterCtrl', function ($scope, $cookieStore,$transitions, Settings, Auth) {
        var self = this;
        var mobileView = 992;
        //for testing......
        $scope.phones = [
            {
                name: 'Nexus S',
                snippet: 'Fast just got faster with Nexus S.'
            }, {
                name: 'Motorola XOOM™ with Wi-Fi',
                snippet: 'The Next, Next Generation tablet.'
            }, {
                name: 'MOTOROLA XOOM™',
                snippet: 'The Next, Next Generation tablet.'
            }
        ];
        //----------------------
        $transitions.onStart({}, function () {
            Auth.getUser().then(function (res) {
                self.user = res.data;
            });
        });

        self.logged = function () {
            return Auth.isAuthorized();
        };

        self.logout = function () {
            Auth.logout();
        };

        $scope.getWidth = function () {
            return window.innerWidth;
        };

        this.menuItems = function () {
            return Settings.getBoxes();
        };

        $scope.$watch($scope.getWidth, function (newValue, oldValue) {
            if (newValue >= mobileView) {
                if (angular.isDefined($cookieStore.get('toggle'))) {
                    $scope.toggle = $cookieStore.get('toggle');
                } else {
                    $scope.toggle = true;
                }
            } else {
                $scope.toggle = false;
            }
        });

        $scope.toggleSidebar = function () {
            $scope.toggle = !$scope.toggle;
            $cookieStore.put('toggle', $scope.toggle);
        };

        window.onresize = function () {
            $scope.$apply();
        };
    });
