'use strict';

/** 
 * @controller PageMainController
 * @property scope 
 * @property location
 * @property route
 * @property System
 * @property PageService
 */

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) {
             System.Page.title("Pages");

            $scope.query = $route.current.params || { };
            $scope.selection = {};

            $scope.a = null;
           

            $scope.treeObject = {};
            
            $(".tooltip").tooltip();

            /**
            * @method refresh
            * @description refreshes page and loads all initial data
            */
            $scope.refresh = function() {
                if ($scope.isSearch()) {
                    PageService.query($scope.query).then(function(data) {
                        $scope.pages = data.pages;
                        $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);
                    });
                }
            };

            /**
            * @method children
            * @description loads children for page
            */
            $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);
                        });
            };

            /**
            * @method isSearch
            * @description returns value indicates if search is running
            */
            $scope.isSearch = function() {
                return Object.keys($scope.query).length !== 0;
            };

            /**
            * @method reset
            * @description resets search to its initial value
            */
            $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);
            };

            /**
            * @action back returns to location /pages
            */
            $scope.back = function() {
                $location.url('/pages');
            };

            /**
            * @action content redirects user to content form
            * @param page
            */
            $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'); }
                   });
            };

            /**
            * @action edit redirects user to edit form
            * @param page
            */
            $scope.edit = function(page) {
                $location.url('/pages/' + page.ID + '/edit');
            };

            /**
            * @action new redirects user to create form
            */
            $scope.new = function() {
                $location.url('/pages/create');
            };

            /**
            * @action new redirects user to create form
            */
            $scope.child = function(id) {
                $location.url('/pages/create/' + id);
            };

            /**
            * @action select selects single page and redirects user to page details
            * @param page page instance to view details for
            */
            $scope.select = function(page) {
                $location.url('/pages/' + page.ID);
            };

            /**
            * @method remove
            * @param page
            * @param index
            * @description removes page by its id and removes it from local page list by its index
            */
            $scope.remove = function(page, index) {
                var r = confirm($scope.$resource('utility.areYouShure'));
                if (r == true) {
                    ContentService.get(page)
                  .then(function (data) {
                      $scope.content = data;
                
                  });
                    if ($scope.content.ID != null) {
                        ContentService.remove({ id: content.ID }).then(function (response) {
                            if (response.Error) {
                                $scope.errors = response.Errors;
                                System.Message.error($scope.$resource("utility.changeNotSave"));
                            } else {
                                $scope.contents.splice(index, 1);
                                System.Message.success($scope.$resource("utility.deleted"));
                            }
                        });
                    }
                   
                    PageService.remove(page)
                        .then(function(data) {
                            if (data.error) {
                                System.Message.error(data.message);
                            } else {
                                $scope.pages.splice(index, 1);
                                System.Message.success($scope.$resource('utility.deleted'));
                            }

                        });
                }
            };

            /**
            * @method link returns to location page.ExternalLink
            * @param page page instance to generate link for
            */
            $scope.root = function(page) {
                PageService.root(page.ID)
                    .then(function () {
                        $scope.refresh();
                        System.Message.success($scope.$resource('pages.home_page'));
                    });
            };

            /**
            * @method sets provided page as a root of current site
            * @param page page instance to set as a root
            */
            $scope.link = function(page) {
                $location.url(page.ExternalLink);
            };

            $scope.tipstranice = function (object) {
                var tip = object;
                if (tip == "Normal")
                    return $scope.$resource('pages.standard');
                if (tip == "Group")
                    return $scope.$resource('pages.group');
                if (tip == "External")
                    return $scope.$resource('pages.external');
                if (tip == "InternalRedirect")
                    return $scope.$resource('pages.internal');
                else
                    return $scope.$resource('pages.standard');
            };

            $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) {
                    }

                }
            };

            /**
           *@property uploadDialog
           */
            $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.refresh();

        }
    ]);