'use strict';

/** 
 * @controller BlogMainController
 * @property scope 
 * @property route
 * @property location
 * @property window
 * @property System
 * @property BlogService
 * @property Resource
 */

var BlogMainController = angular.module('blogs.controllers.main', [
    'system'
])
    .controller('BlogMainController', [
        '$scope',
        '$location',
        '$window',
        '$route',
        'System',
        'BlogService',
        'ClassificationService',
        function ($scope, $location, $window, $route, System, BlogService, ClassificationService) {
             System.Page.title("Blogs");
            $scope.query = $route.current.params || {};
            $scope.sorter = System.Sorter.create($scope.query);
            $scope.blog = {};
            $scope.newBlog = { };
            $scope.sidebarView = 'classifications';
            
            $(".tooltip").tooltip();

            $scope.statuses = [
                { id: 0, title: 'Draft' },
                { id: 1, title: 'Pending' },
                { id: 2, title: 'Live' },
                { id: 3, title: 'Archived' },
                { id: 4, title: 'Deleted' }
            ];
            
            /**
            * @method refresh
            * @description refreshes page and loads all initial data
            */
            $scope.refresh = function() {
                BlogService.query($scope.query).then(function (data) {
                    $scope.blogs = data.blogs;
                    $scope.pager = System.Pager.create({ page: $scope.query.page, total: data.total });
                });

                ClassificationService.query($scope.query)
                    .then(function(data) {
                        $scope.classifications = data.classifications;
                    });
            };
            
            /**
            * @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.refresh();
            };
            
            qusion.queryToArray = function (input, separator) {
                if (!separator) separator = ',';
                if (input && input.indexOf(separator) > -1)
                    input = input.split(separator);
                if (!input)
                    input = [];
                return input;
            };
            
            /**
            * @method search
            * @description searches blogs 
            */
            $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;
            };
            
            /**
            * @method sort
            * @description sorts blogs
            */
            $scope.sort = function (by, dir) {
                $scope.sorter.sort(by, dir);
                $location.search($scope.query);
                $scope.refresh();
            };
            
            /**
            * @action select selects single blog and redirects user to blog details
            * @param blog blog instance to view details for
            */
            $scope.select = function (agent) {
                $location.url('/blogs/' + agent.ID);
            };

            /**
            * @method create
            * @description Creates new blog
            */
            $scope.create = function () {
                BlogService.create($scope.newBlog).then(function (response) {
                    if (response.Errors) {
                        $scope.errors = response.Errors;
                        System.Message.error($scope.$resource('blogs.BlogCreatedError'));
                    } else {
                        $scope.refresh();
                        System.Message.success($scope.$resource('blogs.BlogCreated'));
                    }
                });
            };
            
            $scope.updateBlog = function (blog) {
                $scope.blog = blog;
                $scope.dialogUpdateBlog.dialog("open");
            };

            $scope.dialogUpdateBlog = {};

            $scope.ui.dialogUpdateBlog = {
                width: 700,
                title: $scope.$resource('blogs.update_blog'),
                create: function () {
                    $scope.dialogUpdateBlog = $(this);
                }
            };
            
            /**
            *@method cancelUpdate Close dialog and clears dialog data.
            */
            $scope.cancelUpdate = function () {
                $scope.refresh();
                $scope.dialogUpdateBlog.dialog("close");
            };

            /**
            * @method edit
            * @description Updates blog after successfull edit
            */
            $scope.edit = function () {
                BlogService.edit($scope.blog).then(function (blog) {
                    if (blog.Errors) {
                        $scope.errors = blog.Errors;
                        System.Message.error($scope.$resource('blogs.BlogCreatedError'));
                    } else {
                        $scope.blog = blog;
                        $scope.refresh();
                        $scope.dialogUpdateBlog.dialog("close");
                        System.Message.success($scope.$resource('blogs.BlogUpdated'));
                    }
                    
                });
            };

            /**
            * @method remove
            * @param id
            * @description Removes blog by its id
            */
            $scope.remove = function (blog, index) {
                if ($window.confirm($scope.$resource('utility.areYouShure'))) {
                    BlogService.remove({ id: blog.ID }).then(function (response) {
                        if (response.Error) {
                            $scope.errors = response.Errors;
                            System.Message.error($scope.$resource('utility.changeNotSave'));
                        } else {
                            $scope.blogs.splice(index, 1);
                            System.Message.success($scope.$resource('utility.deleted'));
                        }
                    });
                }
            };
            
            $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();
        }
]);