'use strict';

/** 
 * @controller PageEditController
 * @property scope 
 * @property route
 * @property location
 * @property filter
 * @property System
 * @property PageService
 * @property Resource
 */

var PageEditController = angular.module('pages.controllers.edit', [
    'system'
])
    .controller('PageEditController', [
        '$scope',
        '$route',
        '$location',
        '$filter',
        'System',
        'PageService',
        function($scope, $route, $location, $filter, System, PageService) {
            $scope.Id = $route.current.params["id"];

            /**
            * @method get
            * @param Id
            * @description PageService gets Page data by its id
            */
            PageService.getEdit($scope.Id)
                .then(function(data) {
                    $scope.page = data;
                });

            PageService.top().then(function(data) {

                $scope.pages = qusion.list.jsTree(data.pages);
            });

            /**
            * @method update
            * @description PageService updates Page data after successful edit
            */
            $scope.update = function() {
                if ($scope.page.PageType != 'External')
                    $scope.page.ExternalUrl = null;

                if ($scope.page.PageType != 'InternalRedirect')
                    $scope.page.InternalRedirectID = '';

                PageService.update($scope.page)
                    .then(function(response) {
                        if (response.Errors) {
                            $scope.errors = response.Errors;
                            System.Message.error($scope.$resource('utility.changeNotSave'));
                        } else {
                            $location.url('/pages');
                            System.Message.success($scope.$resource('pages.PageUpdated'));
                        }
                    });
            };

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

            $scope.ui.dialogSelect = {
                width: 715,
                create: function() {

                    $scope.dialogSelect = $(this);
                },
                close: function() {
                    if ($scope.selectionComplete == false) {

                    }
                }
            };

            $scope.selectPages = function() {

                $scope.dialogSelect.dialog("open");
            };

            $scope.treeOptions = {
                selectMode: 1,
                unselectable: $scope.Id,
                dialogTitle: $scope.$resource('pages.select_dialog_title')
            };
        }
    ]);