'use strict';

var VideoMainController = angular.module('videos.controllers.main', [
    'system'
])
    .controller('VideoMainController', [
        '$scope',
        '$http',
        '$route',
        '$location',
        'System',
        'VideoService',
        'LibraryService',
        'ClassificationService',
        '$timeout',
        function ($scope, $http, $route, $location, System, VideoService, LibraryService, ClassificationService, $timeout) {
            
            /**
            * Query object holds entire search data
            */
            $scope.query = $route.current.params || {};
            
            $scope.sidebarView = 'basic';
            
            $(".tooltip").tooltip();

            /**
           *@property disableSort
           *@description Indicates  is sorting disabled or not.
           */
            $scope.disableSort = ($scope.query.libraryId ? false : true);
            
            /**
           *@property isGrid
           *@description  Indicates video dispay mode.
           */
            $scope.isGrid = false;
            
            /**
             *@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 running
            */
            $scope.isSearch = function () {
                return Object.keys($scope.query).length !== 0;
            };
            
            /**
            *@property isEditMode
            *@description  Indicates whether it is possible to change the title of gallerie.
            */
            $scope.isEditMode = false;
            
            /**
            * @method refresh
            * @description Load videos by query params.
            */
            $scope.refresh = function () {
                $scope.ticks = new Date().getTime();
                VideoService.query($scope.query)
                    .then(function (data) {
                        $scope.isGrid = true;
                        $scope.videos = data.Videos;
                        $scope.library = data.Library;
                       
                        if ($scope.library) {
                            $scope.DisableSort = false;
                        } else {
                            $scope.DisableSort = true;
                        }
                        
                        $scope.canLoadMore = data.Videos.length >= 20;
                    });
                
                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;
                    VideoService.query($scope.query)
                        .then(function (data) {
                            $scope.canLoadMore = data.Videos.length >= 20;
                            for (var i = 0; i < data.Videos.length; i++) {
                                $scope.videos.push(data.Videos[i]);
                            }
                        });
                }
            };

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

            /**
            * @method refreshLibraries
            * @description Load libraryes for the user.
            */
            $scope.refreshLibraries = function () {
                VideoService.libraries().then(function (data) {
                    $scope.libraries = data;
                });
            };
            
            $scope.switchSidebar = function (view) {
                $scope.sidebarView = view;
            };
            
           /**
           * @method updateLibrary
           */
            $scope.updateLibrary = function () {
                if ($scope.library.Title != '' || $scope.library.Title != 'undefined') {
                    LibraryService.update($scope.library).then(function (response) {
                        $scope.isEditMode = false;
                        angular.forEach($scope.libraries, function (value, key) {
                            if (value.ID == $scope.library.ID) {
                                $scope.libraries[key] = $scope.library;
                            }
                        });
                    });
                }
            };
            
            /**
            *@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) {
                    VideoService.removeLibrary({ id: id }).then(function (data) {
                                $location.url('/videos/');
                          
                    });
                }
            };
            
            $scope.$watch('isEditMode', function (value) {
                if (value) {
                    $timeout(function () {
                        angular.element("#library-name").focus().select();
                    }, 10);
                }
            });
            
            /**
           *@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.videos.length; i++) {
                        sorted.push($scope.videos[i].ID);
                    }
                    VideoService.organize({ members: sorted }).then(function (data) {
                    });
                },
                disabled: true,
                watchAndRefresh: 'isGrid'
            };
            
            /**
            *@method remove
            *@description Remove video item form library.
            *@param id Video unique identifier
            *@param index Video index in array
            */
            $scope.remove = function (id, index) {
                var r = confirm($scope.$resource('utility.areYouShure'));
                if (r == true) {
                    VideoService.remove({ id: id, permanently: true }).then(function (response) {
                        if (!response.error) {
                            $scope.videos.splice(index, 1);
                            System.Message.success($scope.$resource('utility.deleted'));
                        } else {
                            System.Message.error($scope.$resource('utility.changeNotSave'));
                        }

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

            /**
            * @method all
            * @description Displays all videos regardless to library
            */
            $scope.all = function () {
                $location.url('/videos/');
            };
            
            /**
           *@action upload go to location /videos/upload
           */
            $scope.goToUpload = function () {
                $location.url('/videos/upload');
            };
            
            /**
            *@action goToVideo go to location /video/:Id
            */
            $scope.goToVideo = function (videoId) {
                $location.url('/video/' + videoId);
            };
            
            /**
           * @action goToSettings go to location /videos/settings
           */
            $scope.goToSettings = function () {
                $location.url('/videos/settings');
            };
            

           /**
           *@method all Open dialog for edit video
           */
            $scope.startEditDialog = function (video) {
                $scope.video = video;
                console.log(video);
                if(video.Extension == 'youtube') {
                    $scope.ytEdit.dialog("open");
                }else {
                    $scope.videoEdit.dialog("open");
                }
            };

            /**
            *@method updateYTVideo
            */
            $scope.updateYTVideo = function () {
                $scope.video.LibraryID = $scope.query.libraryId;
                VideoService.editYtVideo($scope.video).then(function (response) {
                    $scope.ytEdit.dialog("close");
                    $scope.searchedVideo = [];
                });
            };
            
           /**
           *@method searchYouTube
           */
          
            $scope.searchYouTube = function () {
                $http.get('https://www.googleapis.com/youtube/v3/search', {
                    params: {
                        key: 'AIzaSyCutNTR_RmFhUWQtXJ_CLeNEieXW8WBqyw',
                        type: 'video',
                        maxResults: '20',
                        part: 'id,snippet',
                        fields: 'items/id,items/snippet/title,items/snippet/description,items/snippet/thumbnails/default,items/snippet/channelTitle',
                        q: $scope.queryYT
                    }
                })
                .success(function (data) {
                    $scope.searchedVideo = data.items;
                })
                .error(function () {
                    $log.info('Search error');
                });
            }
            
            /**
            *@method search
            *@description Search video 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);
            };
            
            /**
            * @method reset
            * @description resets search to its initial value
            */
            $scope.reset = function () {
                $location.search(($scope.query = {}));
            };

            /**
            *@method updateVideo
            */
            $scope.updateVideo = function() {
                if ($scope.video.Title === '') {
                    System.Message.error($scope.$resource('videos.must_title'));
                } else {
                    $scope.video.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.video.Labels.push($scope.Labels[keys[i]][j]);
                        }

                    }
                    
                    if ($scope.upload.waiting().length == 0) {
                        VideoService.editVideo($scope.video).then(function(data) {
                            $scope.upload.clear();
                            $scope.video = { };
                            $scope.refresh();
                            $scope.videoEdit.dialog("close");
                            System.Message.success($scope.$resource('videos.VideoUpdated'));
                        });
                    } else {
                        $scope.upload.send();
                    }
                }
            };
            
            /**
            *@property upload
            *@description upload widget will bee initialized here.
            */
            $scope.upload = {};
            
            /**
            *
            */
            $scope.getSettings = function () {
                VideoService.getSettings()
                    .then(function (data) {
                        $scope.settings = data;
                        $scope.uploadOption = {
                            extensions: $scope.settings.AllowedExtensions.split(','),
                            multiple: false,
                            doneall: function () {
                                $scope.upload.clear();
                                $scope.video = {};
                                $scope.refresh();
                                $scope.videoEdit.dialog("close");
                                System.Message.success($scope.$resource('utility.settingsSaved'));
                            }
                        };
                    });
            };

            $scope.getSettings();
            
            /**
            *
            */
            $scope.ui.ytEdit = {
                width: 700,
                create: function () {
                    $scope.ytEdit = $(this);
                }
            };
            
            /**
            *
            */

            /**
           *
           */
            $scope.cancelSeletion = function () {
                $scope.ytEdit.dialog("close");
            };


            $scope.ui.videoEdit = {
                width: 700,
                create: function () {
                    $scope.videoEdit = $(this);
                }
            };

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