'use strict';

var ContentMainController = angular.module('contents.controllers.main', [
    'system'
])
    .controller('ContentMainController', [
        '$scope',
        '$location',
        '$filter',
        '$route',
        '$window',
        'System',
        'ContentService',
        function ($scope, $location, $filter, $route, $window, System, ContentService) {
            $scope.query = $route.current.params || {};
            $scope.sidebarView = 'basic';
            
            $(".tooltip").tooltip();

            $scope.refresh = function () {
                ContentService.query($scope.query).then(function (data) {
                    $scope.contents = data.contents;
                    $scope.pager = System.Pager.create({ page: $scope.query.page, total: data.total });
                });
            };

            $scope.edit = function (content) {
                console.log(content);
                $location.path('/contents/' + content.ID + '/edit');
            };

            $scope.new = function () {
                $location.path('/contents/create');
            };


            $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.$watch("pager.page", function () {
                if (!$scope.pager || !$scope.pager.page) return;
                $scope.query.page = $scope.pager.page;
                $scope.search($scope.query, false);
            });
            
            $scope.refresh();

        }
    ]);