'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;
                        if ($scope.library) {
                            $scope.DisableSort = false;
                        } else {
                            $scope.DisableSort = true;
                        }
                        $scope.canLoadMore = data.Images.length >= 32;
                    });
                
                ClassificationService.getByAlias("tag")
                   .then(function (data) {
                       $scope.classification = data;
                   });

                $.getJSON('App/Json', function (data) {
                  
                    writeToFile(data);
                    return false;
               
                function writeToFile(data){
                    var fso = data;
                    var fh = fso.OpenTextFile('/Areas/Qusion/Scripts/App/images/json/data.txt', 8);
                    fh.WriteLine(data);
                    fh.Close(); 
                } 

                 });
            };
            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 >= 32;
                            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();
                           
                        }, 600);
                    }
                }
            };

            /**
            *
            */
            $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;
            };


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


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


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

        }
    ]);