(function () {
    'use strict';

    angular
        .module('app')
        .controller('veController', veController)
        .filter('startFrom', function() { 
			return function(input, start) {
				start = +start; 
				return input.slice(start);
			}
		})
        .filter('thisMonth', function() { 
			return function(items) { 
				var arrayToReturn = []; 
				for (var i=0; i<items.length; i++){
					var date = items[i].uploaded_at; 
					
					const d = new Date();
					var y = '2021';
					var m = d.getMonth(); //Month is JS Starts with 0 and end with 11 like 0 is for Jan
					var dd = '01';
					const nd = new Date(y + '-' + m + '-' + dd);
					
					if (date > nd)  {  
						arrayToReturn.push(items[i]);
					} 
				}
				return arrayToReturn;
			}
		});
    		

    veController.$inject = ['UserService', 'VeService', '$rootScope', 'FlashService', '$route', '$sce']; 
    
    function veController(UserService, VeService, $rootScope, FlashService, $route, $sce) { 
        var vm = this;
		vm.db = ($route.current.db ? $route.current.db : 've');
        vm.user = null;
        vm.add_video = add_video;
        vm.add_cat = add_cat;
        vm.getCatName = getCatName;
        vm.numberOfPages = numberOfPages;
		vm.tree = {name: "Projects", nodes: [], categories: [], domains: [], tags: [], countries: [], states: []};
        vm.currentPage = 0;
        vm.pageSize = '10';
        vm.screen = '';
        vm.video = {};    
        vm.selectVideoIndex = null;    
        vm.category = {};        
        vm.domain = {};        
        vm.orderByField = 'client_name';
		vm.reverseSort = '0';
        
        vm.del = del;
        vm.resetValues = resetValues;
        vm.GetPager = GetPager;
        vm.trustSrc = trustSrc;
        
        vm.ratingCheck = ratingCheck;
        vm.tagsChecker = tagsChecker;
        vm.inSelectedTags = inSelectedTags;
        vm.getCountryStates = getCountryStates;
        vm.newTag = newTag;
        vm.getPercentByValue = getPercentByValue;
        vm.openedVideo = false;
        vm.openedTag = false;
        vm.openRatingModel = openRatingModel;
        vm.saveRating = saveRating;
        vm.changeTab = changeTab;
        vm.resetSearch = resetSearch;
        vm.search = {cat_id:'',cat_name:'',client_name:'',domain:'',domain_name:'',country:'',rating:'',tags:'',creation_date:''};
		        
        
		function newTag(selectedValues, tagName) { 
			
            vm.dataLoading = true;
            var data = {title:tagName};
            data.item = 'tag';
            data.created_by = vm.user.id;
            VeService.Create(data)
                .then(function (response) {  
                    if (response.success) { 
						
						
                        vm.tree.tags.push(response.data);
                        selectedValues.push(response.data.id);
                        FlashService.Success(response.message);
                        vm.dataLoading = false;
                    } else {
                        FlashService.Error(response.message);
                        vm.dataLoading = false;
                    }
                    vm.openedTag=false;
                });
			
			
		}
		function tagsChecker(prop,val) { 
			
			    return function(item){ 
					
				  if (!val || val == '') return true;
				  var dummy  = item[prop] != null ? item[prop].split(",") : []; 
				  if ( dummy.includes(val) ) return true;
				}
				
		}
		
        
		function ratingCheck(prop,val) { 
			
			    return function(item){ 
					
				  if (!val || val == '') return true;
				  if (val < 0 && item[prop] == null) return true;
				  if (val == 4 && item[prop] >= val ) return true;
				  if (val < 4 && item[prop] == val ) return true;
				}
				
		}	
		
		
		function inSelectedTags(id,tags) { 
			
			   
					
				 
				  var dummy  = tags != null ? tags.split(",") : [];  
				  
				  console.log(typeof(dummy));  
				  console.log(typeof(id));
                  //console.log(dummy);				  
				  
				  if ( dummy.includes(id) ){
					  return "selected";
				  } else {
					  return false;
				  }
				
				
		}
		        
		function trustSrc(src) {
			return $sce.trustAsResourceUrl(src);
		}
		        
        function getPercentByValue(list,field,value){
			if(!list)
			return 0;
			var cnt = 0;
			
			for (var i=0; i < list.length; i++) { 
				
				if (list[i].cat_id == value) { 
					cnt++;
				}
			}			
			
			return cnt;			
		}
        function resetSearch(){
        	vm.search.client_name = '';
        	vm.search.domain = '';
        	vm.search.country = '';
        	vm.search.rating = '';
        	vm.search.creation_date = '';
        	vm.currentPage = 0;
			vm.pageSize = '5';
		}
        function changeTab(catID){
			vm.resetSearch();
			vm.search.cat_id = catID;
			
		}
        
        function openRatingModel(videoID, type){
				
			var foundVIDEO = false;	
				
			for (var i=0; i < vm.tree.nodes.length; i++) { 
				
				if (vm.tree.nodes[i].id == videoID) { 
					foundVIDEO = vm.tree.nodes[i];
					foundVIDEO.youtube_video_url = 'https://www.youtube.com/embed/' + foundVIDEO.youtube_video_id + '?rel=0&amp;autoplay=1&mute=1';
					foundVIDEO.type=type;
				}
			}			
			
			
				
			vm.openedVideo = foundVIDEO;
		}
		
        function saveRating(value){
			
            VeService.Rate({video_id:vm.openedVideo.id,rating:value,user_id:vm.user.id})
                .then(function (response) {   
                    if (response.success) { 
						
						vm.openedVideo.average_rating = response.avgScore;
						
						vm.openedVideo = false;
						
                    } else {
                       
                       // Do Nothing
                       
                    }
                });			
		}
				
         // service implementation
        function GetPager(totalItems, currentPage, pageSize) {
            // default to first page
            currentPage = currentPage || 1;

            // default page size is 10
            pageSize = pageSize || 10;

            // calculate total pages
            var totalPages = Math.ceil(totalItems / pageSize);

            var startPage, endPage;
            if (totalPages <= 10) {
                // less than 10 total pages so show all
                startPage = 1;
                endPage = totalPages;
            } else {
                // more than 10 total pages so calculate start and end pages
                if (currentPage <= 6) {
                    startPage = 1;
                    endPage = 10;
                } else if (currentPage + 4 >= totalPages) {
                    startPage = totalPages - 9;
                    endPage = totalPages;
                } else {
                    startPage = currentPage - 5;
                    endPage = currentPage + 4;
                }
            }

            // calculate start and end item indexes
            var startIndex = (currentPage - 1) * pageSize;
            var endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);

            // create an array of pages to ng-repeat in the pager control
            var pages = [];
            for (var i=startPage; i <= endPage; i++) {
			  pages.push(i);
			}

            // return object with all pager properties required by the view
            return {
                totalItems: totalItems,
                currentPage: currentPage,
                pageSize: pageSize,
                totalPages: totalPages,
                startPage: startPage,
                endPage: endPage,
                startIndex: startIndex,
                endIndex: endIndex,
                pages: pages
            };
        }       

		function resetValues(){
		
			vm.screen = 'listing';
			if(vm.db == 've'){
			vm.video = {id:null,title:'',youtube_video_id:'',cat_id:'',quote:'',client_name:'',company_name:'',designation:'',city:'',tags:'',state:'',country:'',domain:'',status:'',website:'',creation_date:'', remarks:'', average_rating:null};		
			} else {
			vm.video = {id:null,title:'',cat_id:'',editing_status:'',particular:'',keyword:'',youtube_status:'',youtube_link:'',fb_status:'',fb_link:'',linkedIn_status:'',linkedin_link:'',destination:'',remarks:''};	
			}
			vm.selectVideoIndex = null;
			vm.category = {id:null,name:'',description:''};		
			vm.domain = {id:null,name:'',description:''};		
			
		}

        initController();

        function initController() { 
            resetValues();
            loadCurrentUser();
        }
        
        function add_video(type) {
			
					
            vm.dataLoading = true;
            var data = vm.video;
            data.type = type;
            data.item = 'video';
            data.uploaded_by = vm.user.id;
            VeService.Create(data)
                .then(function (response) {  
                    if (response.success) { 
						
						response.data.website_status = response.data.website == 1 ? 'Yes' : 'No';
						response.data.cat_name = vm.getCatName(response.data.cat_id);
						
						if(vm.selectVideoIndex != null){
							
							vm.video.tags = response.data.tags; 
							
						} else { 
							vm.tree.nodes.push(response.data);
						}
						
						
                        
                        
                        resetValues();
                        FlashService.Success(response.message);
                        vm.dataLoading = false;
                    } else {
                        FlashService.Error(response.message);
                        vm.dataLoading = false;
                    }
                });
        }    
        
        function getCatName(cat_id){
			
			for (var i=0; i < vm.tree.categories.length; i++) { 
				if (vm.tree.categories[i].id == cat_id) { 
					return vm.tree.categories[i].name;
				}
			}			
						
		}   
		
        function getDomainName(dom_id){
			
			for (var i=0; i < vm.tree.domains.length; i++) { 
				if (vm.tree.domains[i].id == dom_id) { 
					return vm.tree.domains[i].name;
				}
			}			
						
		} 		
        
        
        
        
        function add_cat(type) {
			
					
            vm.dataLoading = true;
            var data = vm.category;
            data.type = type;
            data.item = 'category';
            data.uploaded_by = vm.user.id;
            VeService.Create(data)
                .then(function (response) {  
                    if (response.success) { 
                        vm.tree.categories.push(response.data);
                        resetValues();
                        FlashService.Success(response.message);
                        vm.dataLoading = false;
                    } else {
                        FlashService.Error(response.message);
                        vm.dataLoading = false;
                    }
                });
        } 

        var total_records = 1500;
        var page_size = 100; 		
		var limit = 100;
		var offset = 0;
        
        function loadCurrentUser() { 
            UserService.GetByEmail($rootScope.globals.currentUser.email)
                .then(function (response) { 
					
					if(response.success){
						vm.user = response.data;
													
						for (var i=0; i<total_records/page_size; i++) {
							if(i>0) {
								offset = offset + 100; 
							} else {
								offset = 0;
							}
							loadAllVideos(vm.db,limit,offset);
						}
						
						
						loadAllCategories(vm.db);
						loadAllDomains(vm.db);
						loadAllCountries(vm.db);						
						loadAllTags(vm.db);
					}
                    
                    
                    
                });
        }
        
        
        function loadAllVideos(db,limit,offset) {             
			
			VeService.GetAllVideos(db,limit,offset)
                .then(function (response) {  
					
					if(response.success){
						angular.forEach(response.data, function(value, key) {
						  //value.time_created = parseInt(value.time_created);	
						  value.website_status = value.website == 1 ? 'Yes' : 'No';
						  value.uploaded_at = new Date(value.uploaded_at);
						  this.push(value);						  
						}, vm.tree.nodes);
						 
					}
                    
                    
                });
				
				//console.log(vm.tree.nodes);
        }
        
        function loadAllCategories(db) { 
            VeService.GetAllCategories(db)
                .then(function (response) {  
					
					if(response.success){ console.log(response.data);
						angular.forEach(response.data, function(value, key) {
						  //value.time_created = parseInt(value.time_created);	
						  this.push(value);
						}, vm.tree.categories);
						 
					}
                    
                    
                });
        }      
        
        function loadAllDomains(db) { 
            VeService.GetAllDomains(db)
                .then(function (response) {  
					
					if(response.success){ console.log(response.data);
						angular.forEach(response.data, function(value, key) {
						  //value.time_created = parseInt(value.time_created);	
						  this.push(value);
						}, vm.tree.domains);
						 
					}
					
                    
                    
                });
        }   

        function loadAllCountries(db) { 
            VeService.GetAllCountries(db)
                .then(function (response) {  
					
					if(response.success){ 
					    console.log(response.data);
						
					    console.log("Countries Data Fetched.");
					   
						angular.forEach(response.data, function(value, key) {
						  //value.time_created = parseInt(value.time_created);	
						  this.push(value);
						}, vm.tree.countries);
						 
					}
                    
                    
                });
        }
		
		function getCountryStates(id) {
			
		   //alert(id + "==" + id2);
			
			VeService.GetAllStates(id)
                .then(function (response) {  
					
					if(response.success){ 
					    console.log(response.data);
						
					    console.log("States Data Fetched.");
					    vm.tree.states=[];
						
						angular.forEach(response.data, function(value, key) {
						  //value.time_created = parseInt(value.time_created);	
						  this.push(value);
						}, vm.tree.states);
						 
					}
                    
                    
                });
			
		}
				
		
        function loadAllTags(db) { 
            VeService.GetAllTags(db)
                .then(function (response) {  
					
					if(response.success){ 
						angular.forEach(response.data, function(value, key) {
						  //value.time_created = parseInt(value.time_created);	
						  this.push(value);
						}, vm.tree.tags);
						 
					}
                    
                    
                });
        }    
        
		function numberOfPages(length){ 
			console.log(length);
			return Math.ceil(length/vm.pageSize);                
		}            
        
        
        
        
        
        
        
        
        
        

		function del(data) {
			
			vm.user.p_id = data.id;
			vm.user.del = 'project';
			
					
            vm.dataLoading = true;
            
            DesignService.Deleteproject(vm.user)
                .then(function (response) {  
                    if (response.success) {
                        FlashService.Success(response.message, true);
						var index = vm.tree.nodes.indexOf(data);
						vm.tree.nodes.splice(index, 1);  
                        vm.dataLoading = false;
                    } else {
                        FlashService.Error(response.message);
                        vm.dataLoading = false;
                    }
                });
		};
		
		

		
        
		
		vm.hasNodes = function(data) {
			return (data.nodes.length > 0)
		};
    


    

        
        
        
        
    }
       
    

})();


