'use strict';

var EventMainController = angular.module('events.controllers.main', [
    'system'
])
    .controller('EventMainController', [
        '$scope',
        '$location',
        '$filter',
        '$route',
        '$window',
        'System',
        'EventService',
        'ClassificationService',
        function ($scope,$location, $filter, $route, $window, System, EventService, ClassificationService) {
            $scope.query = $route.current.params || {};
            var dt = new Date();
            var dateAsString = $filter('date')(dt, "yyyy-MM-dd'T'HH:mm:ss");
            $scope.formatDate = dateAsString;
            $(".tooltip").tooltip();
            $scope.sorter = System.Sorter.create($scope.query);
            $scope.sidebarView = 'classifications';
            System.Page.title($scope.$resource("events.events"));
            $scope.refresh = function() {
                EventService.query($scope.query).then(function (data) {
                    $scope.events = data.events;
                    $scope.pager = System.Pager.create({ page: $scope.query.page, total: data.total });
                });

                ClassificationService.query($scope.query).then(function(data) {
                    $scope.classifications = data.classifications;
                });
            };

            $scope.select = function (event) {
                $location.url('/events/' + event.ID);
            };
            

            $scope.isSearch = function () {
                return Object.keys($scope.query).length !== 0;
            };


            $scope.reset = function () {
                $location.search(($scope.query = {}));
                $scope.refresh();
            };

            $scope.search = function (q, reset) {
                reset ? $scope.query = q : angular.extend($scope.query, q);
                $location.search($scope.query);
                $scope.refresh();
            };
            
            $scope.switchSidebar = function (view) {
                $scope.sidebarView = view;
            };


            $scope.sort = function (by, dir) {
                $scope.sorter.sort(by, dir);
                $location.search($scope.query);
                $scope.refresh();
            };

            $scope.link = function(event) {
                $location.url(event.ExternalLink);
            };
            
            $scope.$watch("pager.page", function () {
                if (!$scope.pager || !$scope.pager.page) return;
                $scope.query.page = $scope.pager.page;
                $scope.search($scope.query, false);
            });

            $scope.refresh();
        }
    ]);