'use strict';
/** 
 * @controller DocumentMainController
 * @property scope
 * @property route
 * @property location
 * @property System
 * @property DocumentService
 * @property LibraryService
 * @description Manipulations with documents.
*/

angular.module('documents.controllers.main', [
    'system'
])
    .controller('DocumentMainController', [
        '$scope',
        '$route',
        '$location',
        'System',
        'DocumentService',
        'LibraryService',
        'OdjeljenjeService',
        'ClassificationService',
        function ($scope, $route, $location, System, DocumentService, LibraryService,OdjeljenjeService, ClassificationService) {
            System.Page.title("Documenti");
            $scope.classifications = {};
            $(".tooltip").tooltip();
            $scope.sidebarView = 'basic';
            var id = $route.current.params["libraryId"] || "";
            $scope.query = $route.current.params || {};
            $scope.SelectedOdjeljenje = "";
         
            $scope.DocumentSelectorOpiton = {
                multipleSeletcion: false
            };

            /**
         * @property disableSort Indicates  is sorting disabled or not.
          */
            $scope.disableSort = ($scope.query.libraryId ? false : true);

            /**
            * @property isLibrary Indicates for display documents in library or all documents.
            */
            $scope.isLibrary = ($scope.query.libraryId ? true : false);

            /**
            * @method isCurrentLibrary returns value indicates if selected library is same as provided in as argument
            */
            $scope.isCurrentLibrary = function (library) {
                return library.ID == $scope.query.libraryId;
            };

            /**
            *@property isEditMode Indicates whether it is possible to change the title of library.
            */
            $scope.isEditMode = false;

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

            $scope.documents = [];
            /**
         * @method refresh Loads documents by query params.
         */
            $scope.refresh = function () {
                DocumentService.getSettings()
                   .then(function (data) {
                       $scope.settings = data;
                   });

                if ($scope.isLibrary) {
                    DocumentService.query($scope.query)
                        .then(function (data) {
                            $scope.documents = data.documents;
                            $scope.predicateNaziv = 'Title';
                            $scope.pager = System.Pager.create({ page: $scope.query.page, size: $scope.settings.GeneralPageSize, total: data.total });
                        });

                    LibraryService.get(id).then(function (data) {
                        $scope.library = data;
                        $scope.SelectedTip = $scope.library.LibraryTypeID
                        $scope.SelectedOdjel = $scope.library.OdjelID
                        OdjeljenjeService.getForEditOdjel($scope.library.OdjelID).then(function (odjel) {
                            $scope.odjel = odjel;
                            $scope.SelectedOdjeljenje = odjel.OdjeljenjeID;
                        });
                    });
                }
                else {
                     DocumentService.libraries().then(function (data) {
                        $scope.libraries = data;
                        $scope.predicate = '-CreatedOn';
                     });
                        DocumentService.query($scope.query)
                            .then(function (data) {
                                $scope.documents = data.documents;
                                $scope.predicateNaziv = 'Title';
                                $scope.pager = System.Pager.create({ page: $scope.query.page, size: $scope.settings.GeneralPageSize, total: data.total });
                            });
                    }

 
                LibraryService.querytype().then(function (data) {
                    $scope.librarytypes = data.librarytype;
                });

                OdjeljenjeService.query().then(function (data) {
                    $scope.odjeljenja = data.odjeljenja;
                });

                OdjeljenjeService.queryOdjeli().then(function (data) {
                    $scope.odjeli = data.odjeli;
                });

            };

            /*kategorije*/

            $scope.getClassifications = function () {
                ClassificationService.getByAlias('tag').then(function (response) {
                    $scope.tags = response;
                });
                ClassificationService.getByAlias('dokumenti').then(function (response) {
                    $scope.categories = response;
                });
            };

            ClassificationService.getByAlias('dokumenti').then(function (response) {
                $scope.categoriesedit = qusion.list.jsTree(response.Labels, "ID", "Name");
            });

        
            

            $scope.setLockStatusLista = function (library) {
                DocumentService.setLockStatusLista(library.ID).then(function (data) {
                    library.Status = data.Status;

                    if (data.Status == false) {
                        System.Message.success($scope.$resource("utility.changeNotSave"));

                    } else {
                        System.Message.success($scope.$resource("utility.settingsSaved"));
                    }
                });
            };
         
            /**
             * @property upload upload widget will bee initialized here.
             */
            $scope.upload = $('#editfile').upload({
                extensions: ['doc', 'docx', 'pdf', 'xls', 'xlsx', 'ppt', 'pptx']
            }).data("qusion-upload");


            /**
            * @method getSettings Gets upload settings for document.
            */
            $scope.getSettings = function() {
                DocumentService.getSettings()
                    .then(function(data) {
                        $scope.settings = data;
                        $scope.uploadOption = {
                            extensions: $scope.settings.AllowedExtensions,
                            multiple: false,
                            doneall: function() {
                                $scope.upload.clear();
                                $scope.document = { };
                                $scope.refresh();
                                $scope.dialogEdit.dialog("close");
                                System.Message.success($scope.$resource('utility.settingsSaved'));
                            }
                        };
                    });
            };

            $scope.getSettings();

            /**
             * @property upload Upload widget will bee initialized here.
             */
            $scope.upload = { };

         

            /**
          * @method selectLibrary
          * @param id
          * @description Selects library by its id.
          */
            $scope.selectLibrary = function (library,panel) {
               
                $location.url('/documents/' + library + '?panel=' + panel );
            };



            /*Selektovanje po tipu*/
            $scope.selectLibraryType = function (librarytype) {
                LibraryService.GetByLibraryType(librarytype)
                   .then(function (data) {
                       $scope.libst = data.libraries;
                   });
            };
           
         

            /**
            * @method all
            * @description Loads list of all libraries.
            */
            $scope.all = function(view) {
                $location.url('/documents');
                //$scope.sidebarView = view;
            };

            /**
            * @method updateLibrary
            * @description Updates library title
            */
            $scope.updateLibraryDocument = function (library) {
                if ($scope.library.Title != '' || $scope.library.Title != 'undefined') {
                    $scope.library.ID = $scope.query.libraryId;
                    $scope.library.LibraryTypeID = library.LibraryTypeID;
                    $scope.library.ArDatum = library.ArDatum;
                    $scope.library.Status = 0;
                    DocumentService.updateLibrary($scope.library).then(function (response) {
                        if (response.Errors) {
                            $scope.errors = response.Errors;
                            System.Message.error($scope.$resource('documents.LibraryTypeCreatedError'));
                        }
                        else {
                            System.Message.success($scope.$resource('utility.done'));
                            $scope.isEditMode = false;
                        }
                    });

                }
            };


            /**
            * @method removeLibrary
            * @param id
            * @description Removes library by its id.
            */
            $scope.removeLibrary = function (id) {
                var r = confirm($scope.$resource('utility.areYouShure'));
                if (r == true) {
                    DocumentService.removeLibrary({ id: id }).then(function (data) {
                        if (data.Errors) {
                            $scope.errors = data.Errors;
                            System.Message.error($scope.$resource('documents.not_possible_delete_gallery'));
                        } else {
                            angular.forEach($scope.libraries, function (value, key) {
                                if (value.ID == id) {
                                    System.Message.success($scope.$resource('utility.deleted'));
                                    $scope.libraries.splice(key, 1);
                                    $location.url('/documents');                             
                                }
                            });
                        }
                    });
                }
            };

      

            /**
             * @method search
             * @description Search documents by params.
             * @param q object with params.
             * @param value indicating if query should be reseted before applying new values provided in "q" param.
             */
            $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 reset
             * @description resets search to its initial value
             */
            $scope.reset = function () {
                $location.search(($scope.query = {}));
            };

            

            /**
             * @method remove
             * @param id
             * @description Removes document by its id
             */
             $scope.remove = function (id, index) {
                var r = confirm($scope.$resource('utility.areYouShure'));
                if (r == true) {
                    DocumentService.remove({ id: id, permanently: true }).then(function (response) {
                        if (!response.Errors) {
                            $scope.documents.splice(index, 1);
                            $scope.refresh();
                            System.Message.success($scope.$resource('utility.deleted'));
                        } else {
                            System.Message.error($scope.$resource('documents.not_possible_delete_doc'));
                        }

                    });
                }
             };

            /**
            *
            */
            $scope.startEditDialog = function(document) {
                $scope.document = document;
                $scope.Labels = {};
                for (var i = 0; i < $scope.document.Labels.length; i++) {
                    if ($scope.Labels[$scope.document.Labels[i].Classification] == undefined) {
                        $scope.Labels[$scope.document.Labels[i].Classification] = new Array();
                    }
                    $scope.Labels[$scope.document.Labels[i].Classification].push($scope.document.Labels[i].ID);
                }
                $scope.dialogEdit.dialog("open");
            };

            /**
            *
            */
            $scope.cancelEdit = function() {
                $scope.document = { };
                $scope.dialogEdit.dialog("close");
            };

            /**
            *
            */
            $scope.ui.dialogEdit = {
                width: 700,
                title: $scope.$resource('documents.edit_document'),
                create: function() {
                    $scope.dialogEdit = $(this);
                }
            };

            /**
             * @action goToUpload
             * @description returns to location /documents/upload
             */
            $scope.goToUpload = function () {
                var libid = $scope.query.libraryId;
                if (libid != null)
                    $location.url('/documents/upload/' + libid);
                else 
                    $location.url('/documents/upload');
            };

            /**
             * @action goToSettings
             * @description returns to location /documents/settings
             */
            $scope.goToSettings = function() {
                $location.url('/documents/settings');
            };

            /**
         * @action goToUpload
         * @description returns to location /documents/upload
         */
            $scope.addToLibrary = function () {
                $location.url('/documents/upload');
            };

           

            $scope.treeOptions = {
                selectMode: 2,
                dialogTitle: $scope.$resource("articles.select_dialog_categories")
            };

            /**
            * @method startUpload edit document file and title.
            */
            $scope.startUpload = function() {
                if ($scope.document.Title === '') {
                    System.Message.error($scope.$resource('documents.insert_title'));
                } else {
                    $scope.document.Labels = [];
                    var keys = (function (obj) {
                        var k = [], x;
                        for (x in obj) {
                            k.push(x);
                        }
                        return k;
                    })($scope.classifications);

                    for (var i = 0; i < keys.length; i++) {
                        for (var j = 0; j < $scope.classifications[keys[i]].length; j++) {
                            $scope.document.Labels.push($scope.classifications[keys[i]][j]);
                        }

                    }
                    
                    if ($scope.upload.waiting().length == 0) {
                        DocumentService.editDoc($scope.document).then(function(data) {
                            $scope.upload.clear();
                            $scope.document = { };
                            $scope.refresh();
                            $scope.dialogEdit.dialog("close");
                            System.Message.success($scope.$resource('documents.DocumentUpdated'));
                        });
                    } else {
                        $scope.upload.send();
                    }

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

            ///Za demonstraciju selektora.
            $scope.selectedIds = [];

            $scope.selectDocs = function() {
                $scope.dialogSelect.dialog("open");
            };

            $scope.ui.dialogSelect = {
                width: 715,
                title: $scope.$resource('documents.choose_documents'),
                create: function() {
                    $(".ui-widget-header").hide();
                    $scope.selectionComplete = false;
                    $scope.dialogSelect = $(this);
                },
                close: function() {
                    if ($scope.selectionComplete == false) {
                        $scope.selectedIds = [];

                    }
                }
            };


             /*Gleda u selekotvano odjeljenje*/
            $scope.$watch('SelectedOdjel', function (value) {
                if (value) {
                    $scope.OdjelDrop = value;
                    var odjel = value;
                };
            });

            $scope.doneSelection = function() {
                $scope.selectionComplete = true;
                $scope.dialogSelect.dialog("close");
            };
            /*Gleda selektovane parametre i ucitava dokumente */
            $scope.$watch('selectedLibrary', function(value) {
                if (value) {
                    $scope.query = { libraryId: value };
                    $scope.selectedIds = [];
                    $scope.refresh();
                }
            });

            /*Gleda u selektovani tip dokumenta*/
            $scope.$watch('SelectedTip', function (value) {
                if (value) {
                    var odjeljenjeid = $scope.OdjelDrop;
                    var librarytype = value;
                    if (librarytype != null && odjeljenjeid != null) {
                        LibraryService.getByLibraryTypeIOdjel(librarytype, odjeljenjeid)
                        .then(function (data) {
                            $scope.libraries = data;
                        });
                    }
                    if (librarytype != null && odjeljenjeid == null) {
                        LibraryService.GetByLibraryType(librarytype)
                          .then(function (data) {
                              $scope.libraries = data;
                          });
                    }
                }

            });

          

            $scope.cancelSeletion = function() {
                $scope.selectionComplete = false;
                $scope.dialogSelect.dialog("close");
            };

            $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();
            $scope.getClassifications();
         
        }
    ]);