'use strict';

var NavigationMainController = angular.module('navigation.controllers.main', [
    'navigation.services'
])
    .controller('NavigationMainController', [
        '$scope',
        '$rootScope',
        '$location',
        'NavigationService',
        function($scope, $rootScope, $location, NavigationService) {
            // get navigation links
            NavigationService.main($scope.navigationKey)
                .then(function(data) {
                    $scope.menu = data;
                    $scope.active = $scope.menu[0];
                });

          

            // navigates to specified module
            $scope.navigate = function(item) {
                $scope.active = item;
                if (!item.items || item.items.length == 0)
                    $location.url(item.name);
            };

            // determines if provided link is active
            $scope.isActive = function(item) {
                if ($scope.active)
                    return $scope.active.name == item.name;
                return false;
            };

            // watch route changes
            $rootScope.$on("$routeChangeStart", function(event, next, current) {
                var path = $location.path().substring(1, $location.path().length);
                if (!path) {
                    $scope.active = $scope.menu[0];
                    return;
                }

                var name = path.split('/')[0];
                $scope.active = NavigationService.find($scope.menu, name);
            });
        }
    ]);