'use strict';

var PageMainController = angular.module('pages.controllers.main', [
    'system'
])
    .controller('PageMainController', [
        '$scope',
        '$location',
        '$route',
        '$timeout',
        'System',
        'PageService',
        'PageFactory',
        'ContentService',
        function ($scope, $location, $route, $timeout, System, PageService, PageFactory, ContentService) {
            $scope.query = $route.current.params || { };
            $scope.selection = {};
            $scope.a = null;
            $scope.treeObject = {};   
            $(".tooltip").tooltip();

            $scope.refresh = function() {
                if ($scope.isSearch()) {
                    PageService.query($scope.query).then(function(data) {
                        $scope.pages = data.pages;
                        $scope.Title = function (odjeljenja) {
                            return odjeljenja.Title != null;
                        };
                        $scope.pager = System.Pager.create({ page: $scope.query.page, total: data.total });
                    });
                } else {
                    PageService.top().then(function (data) {
                        $scope.strane = qusion.list.jsTree(data.pages);
                        $scope.pages = qusion.list.hierarchy(data.pages);
                        console.log($scope.pages);
                        $timeout(function () {
                           
                            $("#treeTable").treetable({
                                expandable: true,
                                column: 1,
                                expanderTemplate: '<a href="#">&nbsp;</a>',
                                indenterTemplate: '<span class="indenter">&nbsp</span>',
                                onNodeCollapse: function () {
                                    PageFactory.removeExpanded(this.id);
                                },
                                onNodeExpand: function (e) {
                                    PageFactory.addExpanded(this.id);
                                }
                            });
                           
                            var expanded = PageFactory.allExpanded();
                            for (var i = 0; i < expanded.length; i++) {
                                $("#treeTable").treetable("expandNode", expanded[i]);
                            }
                           
                        }, 100);
                    });
                }
            };

            $scope.children = function(page, event) {
                if (!page.Children || page.Children.length == 0)
                    PageService.top({ parentId: page.ID })
                        .then(function(data) {
                            page.Children = page.Children || [];
                            page.Children.push(data.pages);
                        });
            };

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

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

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

            $scope.back = function() {
                $location.url('/pages');
            };

            $scope.content = function (page) {
                ContentService.getEditPage(page.ID)
                   .then(function (data) {
                       $scope.content = data;
                       var id = $scope.content.ID;
                       if (id != null)
                       { $location.url('/contents/' + id + '/edit'); }
                       else
                       { $location.url('/contents/' + page.ID + '/create'); }
                   });
            };

           
            $scope.child = function(id) {
                $location.url('/pages/create/' + id);
            };

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

            $scope.root = function(page) {
                PageService.root(page.ID)
                    .then(function () {
                        $scope.refresh();
                        System.Message.success($scope.$resource('pages.home_page'));
                    });
            };


            $scope.link = function(page) {
                $location.url(page.ExternalLink);
            };

            $scope.treeOptions = {
                dnd: {
                    onDragStart: function (node) {
                        return true;
                    },
                    onDragStop: function (node) {
                        $scope.reordered = qusion.list.jsTreeOrdered($scope.treeObject.toDict().children);
                        $scope.$apply();
                      
                    },
                    autoExpandMS: 1000,
                    preventVoidMoves: true, 
                    onDragEnter: function (node, sourceNode) {
                       
                        return true;
                    },
                    onDragOver: function (node, sourceNode, hitMode) {
                       
                        if (node.isDescendantOf(sourceNode)) {
                            return false;
                        }
                       
                        if (!node.data.isFolder && hitMode === "over") {
                            return "after";
                        }
                    },
                    onDrop: function (node, sourceNode, hitMode, ui, draggable) {
                        sourceNode.move(node, hitMode);
                       
                    },
                    onDragLeave: function (node, sourceNode) {
                    }

                }
            };

            $scope.ui.reorderDialog = {
                width: 700,
                title: $scope.$resource('pages.reordering'),
                create: function () {
                    $scope.reorderDialog = $(this);
                }
            };

            $scope.openReordering = function() {
                $scope.reorderDialog.dialog("open");
            };

            $scope.doneReordering = function() {
                PageService.reorder($scope.reordered).then(function(data) {
                    System.Message.success($scope.$resource('utility.settingsSaved'));
                    $scope.reorderDialog.dialog("close");
                    $scope.refresh();
                });
            };
            
            $scope.cancelReordering = function () {
                $scope.reorderDialog.dialog("close");
            };

            $scope.selectLibrary = function (tip) {
                if (tip != null)
                    $location.url('/documents/' + tip);
                else
                    $location.url('/documentst/');
            };

            $scope.refresh();

        }
    ]);