'use strict';
/**
     *@class ImagesMainController
     *@description Manipulations with images.
     */
var ImagesMainController = angular.module('images.controllers.main', [
    'system'
])
    .controller('ImagesMainController', [
        '$scope',
        '$route',
        '$location',
        'System',
        'ImageService',
        'LibraryService',
        'ClassificationService',
        '$timeout',
        '$http',

        function ($scope, $route, $location, System, ImageService, LibraryService, ClassificationService, $timeout, $http) {
            $(".tooltip").tooltip();

            /**
            * Query object holds entire search data
            */
            $scope.query = $route.current.params || { };

            $scope.sidebarView = 'basic';

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


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

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

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

            /**
            *@property isGrid
            *@description  Indicates the pictures dispay mode.
            */
            $scope.isGrid = false;

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

            angular.extend($scope.query, $route.current.params);

            /**
            *
            */
            $scope.images = [];

            /**
            * @method refresh
            * @description Load images by query params.
            */
            $scope.refresh = function() {
                $scope.ticks = new Date().getTime();
                ImageService.query($scope.query)
                    .then(function(data) {
                        $scope.isGrid = true;
                        $scope.images = data.Images;
                        $scope.library = data.Library;
                        $scope.predicate = '-CreatedOn';
                        if ($scope.library) {
                            $scope.DisableSort = false;
                        } else {
                            $scope.DisableSort = true;
                        }
                        if (data.Images.length >= 18)
                        $scope.canLoadMore = true;
                    });
                
                ClassificationService.getByAlias("tag")
                   .then(function (data) {
                       $scope.classification = data;
                   });

               
            };


            var page = 1;
            $scope.loadMore = function() {
                $scope.ticks = new Date().getTime();
                if ($scope.canLoadMore) {
                    $scope.query.page = ++page;
                    ImageService.query($scope.query)
                        .then(function(data) {
                            $scope.canLoadMore = data.Images.length >= 14;
                            for (var i = 0; i < data.Images.length; i++) {
                                $scope.images.push(data.Images[i]);
                            }
                        });
                }
            };

            var timeout;
            $scope.scrollOptions = {
                scrollBottom: function (event, element) {
                    if (element.hasClass('scroller')) {
                        clearTimeout(timeout);

                        timeout = setTimeout(function() {
                            $scope.loadMore();
                           
                        }, 300);
                    }
                }
            };

            /**
            *
            */
            $scope.getSettings = function() {
                ImageService.getSettings()
                    .then(function(data) {
                        $scope.settings = data;
                        console.log($scope.settings);
                        $scope.uploadOption = {
                            extensions: $scope.settings.AllowedExtensions,
                            multiple: false,
                            doneall: function() {
                                $scope.upload.clear();
                                $scope.image = { };
                                $scope.refresh();
                                $scope.dialogEdit.dialog("close");
                                System.Message.success($scope.$resource('utility.settingsSaved'));
                            }
                        };
                    });
            };

            $scope.getSettings();

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

            /**
            * @method lib
            * @description Loads images for provided library.
            */
            $scope.lib = function(library) {
                $location.url('/images/' + library.ID);
            };

            /**
            * @method all
            * @description Displays all images regardless to library
            */
            $scope.all = function() {
                $location.url('/images/');
            };

            /**
            * @method refreshLibraries
            * @description Load libraryes for the user.
            */
            $scope.refreshLibraries = function() {
                ImageService.libraries().then(function(data) {
                    $scope.libraries = data;
                });
       
            };

            /**
            *@property sortableOptions
            *@description Necessary options to initialize sortable widget.
            */
            $scope.sortableOptions = {
                connectWith: ".sort-item",
                handle: '.ui-command-drag',
                stop: function(e, ui) {
                    var sorted = [];
                    for (var i = 0; i < $scope.images.length; i++) {
                        sorted.push($scope.images[i].ID);
                    }
                    ImageService.organize({ members: sorted }).then(function(data) {
                    });
                },
                disabled: true,
                watchAndRefresh: 'isGrid'
            };

            /**
            *@method search
            *@description Search images by params.
            *@param q object with params.
            *@param value indicating if query should be reset 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);
            };
            
            /**
            * @method reset
            * @description resets search to its initial value
            */
            $scope.reset = function () {
                $location.search(($scope.query = {}));
            };
            
            $scope.switchSidebar = function (view) {
                $scope.sidebarView = view;
            };

            /**
            *@method remove
            *@description Remove image item form library.
            *@param id Image unique identifier
            *@param index Image index in array
            */
            $scope.remove = function(id, index) {
                var r = confirm($scope.$resource('utility.areYouShure'));
                if (r == true) {
                    ImageService.remove({ id: id, permanently: true }).then(function(response) {
                        if (!response.Errors) {
                            $scope.images.splice(index, 1);
                            System.Message.success($scope.$resource('utility.deleted'));
                        } else {
                            System.Message.error($scope.$resource('images.not_possible_delete_image'));
                        }

                    });
                }
            };

            /**
            *
            */

            $scope.updateLibrary = function () {
                if ($scope.library.Title != '' || $scope.library.Title != 'undefined') {
                    $scope.library.ID = $scope.query.libraryId;
                    $scope.library.Status = 5;
                    ImageService.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;
                        }
                    });
      
                }
            };

            $scope.$watch('isEditMode', function(value) {
                if (value) {
                    $timeout(function() {
                        angular.element("#library-name").focus().select();
                    }, 10);
                }
            });

            /**
            *@method removeLibrary
            *@description Remove library and images form it.
            *@param id Library id.
            */
            $scope.removeLibrary = function(id) {
                var r = confirm($scope.$resource('utility.areYouShure'));
                if (r == true) {
                    ImageService.removeLibrary({ id: id }).then(function (data) {
                        if (data.Errors) {
                            $scope.errors = data.Errors;
                            System.Message.error($scope.$resource('images.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('/images');
                                }
                            });
                        }
                    });
                }
            };

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


            /**
            *@method cancelEdit Close dialog and clear edit dialog.
            */
            $scope.cancelEdit = function() {
                $scope.upload.clear();
                $scope.image = { };
                $scope.dialogEdit.dialog("close");
            };

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

            /**
            @action upload go to location /images/upload
            */
            $scope.goToUpload = function() {
                $location.url('/images/upload');
            };

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

            /**
            *@method startUpload edit image file and title.
            */
            $scope.startUpload = function() {

                if ($scope.image.Title === '') {
                    System.Message.error($scope.$resource('images.insert_title'));
                } else {
                    
                    $scope.image.Labels = [];
                    var keys = (function (obj) {
                        var k = [], x;
                        for (x in obj) {
                            k.push(x);
                        }
                        return k;
                    })($scope.Labels);

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

                    }
                   
                    if ($scope.upload.waiting().length == 0) {
                        ImageService.editImage($scope.image).then(function (data) {
                            $scope.upload.clear();
                            $scope.image = { };
                            $scope.refresh();
                            $scope.dialogEdit.dialog("close");
                            System.Message.success($scope.$resource('images.ImageUpdated'));
                        });
                    } else {
                        $scope.upload.send();
                    }
                }
            };

            $scope.refresh();
            $scope.refreshLibraries();

        }
    ]);