appice.controller('usagePageController', function ($scope, appIceService, $routeParams, $location) {
	var semusiCustomEvents = {};
	$scope.userChart = true;
	$scope.avgSessionChart = true;
	$scope.sessionChart = true;
	
	$scope.initDateRange = function () {
		$("#advance-daterange").show();
		$('#advance-daterange span').html(moment().subtract('days', 29).format(semusiCommon.getDateFormatt()) + ' - ' + moment().format(semusiCommon.getDateFormatt()));

		getActiveUserSessionStats();
		getActiveUserTimelySessions();
		
		$('#advance-daterange').daterangepicker({
			format: semusiCommon.getDateFormatt(),
			startDate: moment().subtract(29, 'days'),
			endDate: moment(),
			minDate: '01/01/2012',
			maxDate: new Date(),
			dateLimit: { days: 365 },
			showDropdowns: true,
			showWeekNumbers: false,
			timePicker: false,
			timePickerIncrement: 1,
			timePicker12Hour: true,
			ranges: {
				'Today': [moment(), moment()],
				'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
				'Last 7 Days': [moment().subtract(6, 'days'), moment()],
				'Last 30 Days': [moment().subtract(29, 'days'), moment()],
				'This Month': [moment().startOf('month'), moment().endOf('month')],
				'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
			},
			opens: 'left',
			drops: 'down',
			buttonClasses: ['btn', 'btn-sm'],
			applyClass: 'btn-primary',
			cancelClass: 'btn-default',
			separator: ' to ',
			locale: {
				applyLabel: 'Submit',
				cancelLabel: 'Cancel',
				fromLabel: 'From',
				toLabel: 'To',
				customRangeLabel: 'Custom',
				daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
				monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
				firstDay: 1
			}
		}, function (start, end, label) {

			semusiCommon.setDateRange(start, end);
			$('#advance-daterange span').html(start.format(semusiCommon.getDateFormatt()) + ' - ' + end.format(semusiCommon.getDateFormatt()));

			$('.ms-drop').find("ul").remove();
			getActiveUserSessionStats();
			getActiveUserTimelySessions();
		});
	}

    $scope.toggleUsersChart = function() {
		$scope.userChart = !$scope.userChart;
		if($scope.userChart==true){
			$("#users_table").hide();
			$("#users_chart").show();
		}
		else{
			$("#users_table").show();
			$("#users_chart").hide();	
		}
		 
		$scope.populateActiveUsersChunk();
	}

	$scope.toggleAvgSession = function(){
		$scope.avgSessionChart = !$scope.avgSessionChart;
		if($scope.avgSessionChart==true){
			$("#averageSessionTable").hide();
			$("#averageSessionChart").show();
		}
		else{
			$("#averageSessionTable").show();
			$("#averageSessionChart").hide();	
		}
		 
		$scope.populateAverageUsersChunk();
	}

	$scope.toggleSessionChart = function(){
		$scope.sessionChart = !$scope.sessionChart;
		if($scope.sessionChart==true){
			$("#sessionTable").hide();
			$("#sessionChart").show();
		}
		else{
			$("#sessionTable").show();
			$("#sessionChart").hide();	
		}
		 
		$scope.populateTimelySessionsChunk();
	}

	$scope.populateActiveUsersChunk = function () {
		if(semusiCustomEvents.activeUserData){
			var tableData = [];
			var platform = $("#ddlPlatform").val();
			var platfroms = ['android','ios','web'];
			var appNames = []
			var currentTotal = 0;
			var previousTotal = 0;
			semusiCustomEvents.activeUserData.ten_plus = 0;
			semusiCustomEvents.activeUserData.eight_to_ten = 0;
			semusiCustomEvents.activeUserData.six_to_eight = 0;
			semusiCustomEvents.activeUserData.two_to_five = 0;
			semusiCustomEvents.activeUserData.one = 0;
	  
			if(platform=="all"){
				platfroms.forEach(function(p){
				   currentTotal += semusiCustomEvents.activeUserData[p]['currentU'];
				   previousTotal += semusiCustomEvents.activeUserData[p]['previousU'];
	  
				   appNames =  _.union(Object.keys(semusiCustomEvents.activeUserData[p]), Object.keys(semusiCustomEvents.activeUserData[p]));
				   appNames.forEach(function(app){
					  if(app != 'currentU'
						&& app != 'previousU'
						&& app != 'currentTsd'
						&& app != 'previousTsd'
						&& app != 'previousTotalSc'
						&& app != 'currentTotalSc'
					  ){
						  if(semusiCustomEvents.activeUserData[p][app]['au']){
							  if(semusiCustomEvents.activeUserData[p][app]['au']['10+']){
								 semusiCustomEvents.activeUserData.ten_plus += semusiCustomEvents.activeUserData[p][app]['au']['10+'];
							  }
							  if(semusiCustomEvents.activeUserData[p][app]['au']['8-10']){
								 semusiCustomEvents.activeUserData.eight_to_ten += semusiCustomEvents.activeUserData[p][app]['au']['8-10'];
							  }
							  if(semusiCustomEvents.activeUserData[p][app]['au']['6-8']){
								 semusiCustomEvents.activeUserData.six_to_eight += semusiCustomEvents.activeUserData[p][app]['au']['6-8'];
							  }
							  if(semusiCustomEvents.activeUserData[p][app]['au']['2-5']){
								 semusiCustomEvents.activeUserData.two_to_five += semusiCustomEvents.activeUserData[p][app]['au']['2-5'];
							  }
							  if(semusiCustomEvents.activeUserData[p][app]['au']['1']){
								 semusiCustomEvents.activeUserData.one += semusiCustomEvents.activeUserData[p][app]['au']['1'];
							  }
						  }
					  }
				   });
				});
	  
			}else{
				currentTotal += semusiCustomEvents.activeUserData[platform]['currentU'];
				previousTotal += semusiCustomEvents.activeUserData[platform]['previousU'];
				appNames =  _.union(Object.keys(semusiCustomEvents.activeUserData[platform]), Object.keys(semusiCustomEvents.activeUserData[platform]));
				appNames.forEach(function(app){
					if(app != 'currentU'
						&& app != 'previousU'
						&& app != 'currentTsd'
						&& app != 'previousTsd'
						&& app != 'previousTotalSc'
						&& app != 'currentTotalSc'
					){
					  if(semusiCustomEvents.activeUserData[platform][app]['au']){
						  if(semusiCustomEvents.activeUserData[platform][app]['au']['10+']){
							 semusiCustomEvents.activeUserData.ten_plus += semusiCustomEvents.activeUserData[platform][app]['au']['10+'];
						  }
						  if(semusiCustomEvents.activeUserData[platform][app]['au']['8-10']){
							 semusiCustomEvents.activeUserData.eight_to_ten += semusiCustomEvents.activeUserData[platform][app]['au']['8-10'];
						  }
						  if(semusiCustomEvents.activeUserData[platform][app]['au']['6-8']){
							 semusiCustomEvents.activeUserData.six_to_eight += semusiCustomEvents.activeUserData[platform][app]['au']['6-8'];
						  }
						  if(semusiCustomEvents.activeUserData[platform][app]['au']['2-5']){
							 semusiCustomEvents.activeUserData.two_to_five += semusiCustomEvents.activeUserData[platform][app]['au']['2-5'];
						  }
						  if(semusiCustomEvents.activeUserData[platform][app]['au']['1']){
							 semusiCustomEvents.activeUserData.one += semusiCustomEvents.activeUserData[platform][app]['au']['1'];
						  }
					  }
					}
			   });
			}
	  
			$("#lblActiveUsers").text(nFormatter(parseInt(currentTotal)));
			changedTotal = currentTotal-previousTotal;
			 
			var percentChange = (previousTotal==0)? 100: parseFloat(changedTotal/previousTotal*100).toFixed(2);
			var strPercentChange;
			var changeSign;
			if(percentChange>0 && percentChange<200){
				changeSign = '<div style="font-size:14px; color:#000;"><i class="fa fa-2x fa-caret-up"></i></div>'
				strPercentChange = parseInt(percentChange) +' %';
			}else if(percentChange>200){
				changeSign = '<div style="font-size:14px; color:#000;"><i class="fa fa-2x fa-caret-up"></i></div>'
				strPercentChange = '10%';
			}
			else if(percentChange<0){
				percentChange=percentChange*-1;
				changeSign = '<div style="font-size:14px; color:#000;"><i class="fa fa-2x fa-caret-down"></i></div>';
				strPercentChange = parseInt(percentChange) +' %';
			}
			else if(percentChange==0){
				changeSign ='';
				strPercentChange = parseInt(percentChange) +' %';
			}
			if(previousTotal==0){
				strPercentChange = 'NA';
				changeSign ='';
			}
	  
			$("#tdSign").html(changeSign);
			$("#lblChangeActiveUsers").text(strPercentChange);
	  
			tableData.push(["10+",semusiCustomEvents.activeUserData.ten_plus]);
			tableData.push(["8-10",semusiCustomEvents.activeUserData.eight_to_ten]);
			tableData.push(["6-8",semusiCustomEvents.activeUserData.six_to_eight]);
			tableData.push(["2-5",semusiCustomEvents.activeUserData.two_to_five]);
			tableData.push(["1",semusiCustomEvents.activeUserData.one]);
	  
			 
			$('#tblActiveUsers > tbody >tr').remove();
			tableData.forEach(function(item){
				$('#tblActiveUsers > tbody').append('<tr ><td style="padding:3px;">' + item[0]  +'</td><td style="padding:3px;text-align:right">'+ item[1]  +'</td></tr>');
			});
		  }

		if($scope.userChart == true){  
		    let container = document.getElementById('users_chart'); 
			while (container.firstChild) {
                container.removeChild(container.firstChild);
            }
            
			//Bar chart starts
			//preparing chart data
			let chartData = tableData.map(data =>{
				return {
					x: data[0] + ' Sessions',
					value: data[1],
					legendItem: {
						iconType: "circle",
					  }
				}
			});
				// create a chart
				var chart = anychart.pie(chartData);
				anychart.licenseKey("semusi.com-df30754a-aa10847e");
				var credits = chart.credits();
				credits.url("https://demo.appice.io/login");
				credits.logoSrc("https://demo.appice.io/assets/img/icon-title.png");
				credits.text("appICE");
	
				let legend = chart.legend();
				
			
				// enables legend
				legend.enabled(true);
				// set legend height
				legend.height(250);
				// set legend width
				legend.width(125);
				// set legend position
				legend.position("right");
				// set legend align
				legend.align("center");
				// legend items layout
				legend.itemsLayout("vertical");

				// create a bar series and set the data
				// var series = chart.column(chartData);

				// set the container id
				chart.container("users_chart");

				// initiate drawing the chart
				chart.draw();
		 }



	}

	$scope.populateTimelySessionsChunk = function () {
		var currentTotal = 0;
		var previousTotal = 0;
		var changedTotal = 0;

		var tableData = [
			{
				time: 'Morning',
				total: 0,
				places: [
					{
						p: 'Home',
						total: 0
					},
					{
						p: 'Office',
						total: 0
					},
					{
						p: 'Other',
						total: 0
					}
				]
			},
			{
				time: 'Afternoon',
				total: 0,
				places: [
					{
						p: 'Home',
						total: 0
					},
					{
						p: 'Office',
						total: 0
					},
					{
						p: 'Other',
						total: 0
					}
				]
			},
			{
				time: 'Evening',
				total: 0,
				places: [
					{
						p: 'Home',
						total: 0
					},
					{
						p: 'Office',
						total: 0
					},
					{
						p: 'Other',
						total: 0
					}
				]
			},
			{
				time: 'Night',
				total: 0,
				places: [
					{
						p: 'Home',
						total: 0
					},
					{
						p: 'Office',
						total: 0
					},
					{
						p: 'Other',
						total: 0
					}
				]
			},
			{
				time: 'Midnight',
				total: 0,
				places: [
					{
						p: 'Home',
						total: 0
					},
					{
						p: 'Office',
						total: 0
					},
					{
						p: 'Other',
						total: 0
					}
				]
			}
		];


		var platform = $("#ddlPlatform").val();
		if (semusiCustomEvents.timelyCurrentData) {

			semusiCustomEvents.timelyCurrentData.forEach(function (item, key) {

				var platformName = Object.keys(item)[0]; // get all platforms from object keys
				var index = 0;
				if (platformName && (platformName.toLowerCase() == platform || platform == "all")) {
					item[platformName].forEach(function (value, keys) {
						var time = Object.keys(value)[0]; // get all times from object keys

						if (tableData) {
							var timeFlag = false;
							tableData.forEach(function (times, key) { // check time push into array or not
								if (times.time.toLowerCase() == time) {
									timeFlag = true;
									index = key;
									return;
								}
							});

							/*if(!timeFlag){ // push if time key not exists into array
							  var obj = {time:time, total:0};
							  tableData.push(obj);
							  index = (tableData.length-1); // get index of time 
							}*/
						} else { // push if time key not exists into array
							/*var obj = {time:time, total:0};
							tableData.push(obj);*/
						}

						var places = Object.keys(value[time]); // get all places key
						places.forEach(function (place) {
							tableData[index].total += value[time][place]; // some of time
							currentTotal += value[time][place];
							// total according places
							tableData[index].places.forEach(function (elem, pos) {
								if (elem.p.toLowerCase() == place) {
									tableData[index].places[pos].total += value[time][place];
								}
							})

						});
					});
				}
				previousTotal += semusiCustomEvents.timelyPreviousData[platformName];
			});

			$("#lblSessions").text(nFormatter(parseInt(currentTotal))); // total session
			changedTotal = currentTotal - previousTotal;
			percentChange = (previousTotal == 0) ? 100 : parseFloat(changedTotal / previousTotal * 100).toFixed(2);
			var strPercentChange;
			var changeSign;
			if (percentChange > 0 && percentChange<200) {
				changeSign = '<div style="font-size:14px; color:#000;"><i class="fa fa-2x fa-caret-up"></i></div>'
				strPercentChange = parseInt(percentChange) + ' %';
			}else if(percentChange>200){
				changeSign = '<div style="font-size:14px; color:#000;"><i class="fa fa-2x fa-caret-up"></i></div>'
				strPercentChange = '13%';
			}else if (percentChange < 0) {
				percentChange = percentChange * -1;
				changeSign = '<div style="font-size:14px; color:#000;"><i class="fa fa-2x fa-caret-down"></i></div>';
				strPercentChange = parseInt(percentChange) + ' %';
			}
			else if (percentChange == 0) {
				changeSign = '';
				strPercentChange = parseInt(percentChange) + ' %';
			}
			if (previousTotal == 0) {
				strPercentChange = 'NA';
				changeSign = '';
			}
			$("#tdSignSessions").html(changeSign);
			$("#lblChangeSessions").text(strPercentChange); //previous data

			$('#tblSessions > tbody >tr').remove();
			tableData.forEach(function (item) {
				var html = '<tr ><td style="padding:3px; ">' + item.time + '</td>';

				item.places.forEach(function (place) {
					html += '<td style="padding:3px;text-align:right ">' + place.total + '</td>';
				});

				html += '<td style="padding:3px;text-align:right">' + item.total + '</td></tr>';
				$('#tblSessions > tbody').append(html);
			});
		}

		 

		if($scope.sessionChart == true){  

			let container = document.getElementById('sessionChart'); 
			while (container.firstChild) {
                container.removeChild(container.firstChild);
            }
            
		//prepare heatmap data
		let heatmap_data = tableData.map(ele =>{
			let data = []
		     ele.places.forEach(place => {
				 let x = ele.time;
				 let y = place.p;
				 let heat = place.total;
				 let obj = {
					 x:x,y:y,heat:heat
				 }
				 data.push(obj);
			 })
			 return data;
		});
        let chartData = [];
		for(let i=0;i<heatmap_data.length;i++){
			for(let j=0;j<heatmap_data[i].length;j++){
				chartData.push(heatmap_data[i][j])
			}
		}
		 

				// create a chart and set the data
		var chart = anychart.heatMap(chartData);

		anychart.licenseKey("semusi.com-df30754a-aa10847e");
		var credits = chart.credits();
		credits.url("https://demo.appice.io/login");
		credits.logoSrc("https://demo.appice.io/assets/img/icon-title.png");
		credits.text("appICE");

		// configure labels
		chart.labels().format("{%heat}");

		// configure tooltips
		chart.tooltip().format("{%y}: {%heat}");

		chart.container("sessionChart");

		// initiate drawing the chart
		chart.draw();
	  }

	}

	$scope.populateAverageUsersChunk = function () {
		if (semusiCustomEvents.activeUserData) {
			var tableData = [];
			var platform = $("#ddlPlatform").val();
			var platfroms = ['android', 'ios'];
			var appNames = []
			var currentTotal = 0;
			var previousTotal = 0;
			var currentU = 0;
			var previousU = 0;
			semusiCustomEvents.averageUserChunk = {};
			semusiCustomEvents.averageUserChunk.five_plus = 0;
			semusiCustomEvents.averageUserChunk.three_to_five = 0;
			semusiCustomEvents.averageUserChunk.one_to_three = 0;
			semusiCustomEvents.averageUserChunk.half_to_one = 0;
			semusiCustomEvents.averageUserChunk.less_than_thirtysec = 0;

			if (platform == "all") {
				platfroms.forEach(function (p) {
					currentTotal += semusiCustomEvents.activeUserData[p]['currentTsd'];
					previousTotal += semusiCustomEvents.activeUserData[p]['previousTsd'];
					currentU += semusiCustomEvents.activeUserData[p]['currentTotalSc']
					previousU += semusiCustomEvents.activeUserData[p]['previousTotalSc']

					appNames = _.union(Object.keys(semusiCustomEvents.activeUserData[p]), Object.keys(semusiCustomEvents.activeUserData[p]));
					appNames.forEach(function (app) {
						if (app != 'currentU'
							&& app != 'previousU'
							&& app != 'currentTsd'
							&& app != 'previousTsd'
							&& app != 'previousTotalSc'
							&& app != 'currentTotalSc'
						) {
							if (semusiCustomEvents.activeUserData[p][app]['asl']) {
								if (semusiCustomEvents.activeUserData[p][app]['asl']['5+']) {
									semusiCustomEvents.averageUserChunk.five_plus += semusiCustomEvents.activeUserData[p][app]['asl']['5+'];
								}
								if (semusiCustomEvents.activeUserData[p][app]['asl']['3-5']) {
									semusiCustomEvents.averageUserChunk.three_to_five += semusiCustomEvents.activeUserData[p][app]['asl']['3-5'];
								}
								if (semusiCustomEvents.activeUserData[p][app]['asl']['1-3']) {
									semusiCustomEvents.averageUserChunk.one_to_three += semusiCustomEvents.activeUserData[p][app]['asl']['1-3'];
								}
								if (semusiCustomEvents.activeUserData[p][app]['asl']['0:5-1']) {
									semusiCustomEvents.averageUserChunk.half_to_one += semusiCustomEvents.activeUserData[p][app]['asl']['0:5-1'];
								}
								if (semusiCustomEvents.activeUserData[p][app]['asl']['<30']) {
									semusiCustomEvents.averageUserChunk.less_than_thirtysec += semusiCustomEvents.activeUserData[p][app]['asl']['<30'];
								}
							}
						}
					});
				});

			} else {
				currentTotal += semusiCustomEvents.activeUserData[platform]['currentTsd'];
				previousTotal += semusiCustomEvents.activeUserData[platform]['previousTsd'];
				currentU += semusiCustomEvents.activeUserData[platform]['currentTotalSc']
				previousU += semusiCustomEvents.activeUserData[platform]['previousTotalSc']

				appNames = _.union(Object.keys(semusiCustomEvents.activeUserData[platform]), Object.keys(semusiCustomEvents.activeUserData[platform]));
				appNames.forEach(function (app) {
					if (app != 'currentU'
						&& app != 'previousU'
						&& app != 'currentTsd'
						&& app != 'previousTsd'
						&& app != 'previousTotalSc'
						&& app != 'currentTotalSc'
					) {
						if (semusiCustomEvents.activeUserData[platform][app]['asl']) {
							if (semusiCustomEvents.activeUserData[platform][app]['asl']['5+']) {
								semusiCustomEvents.averageUserChunk.five_plus += semusiCustomEvents.activeUserData[platform][app]['asl']['5+'];
							}
							if (semusiCustomEvents.activeUserData[platform][app]['asl']['3-5']) {
								semusiCustomEvents.averageUserChunk.three_to_five += semusiCustomEvents.activeUserData[platform][app]['asl']['3-5'];
							}
							if (semusiCustomEvents.activeUserData[platform][app]['asl']['1-3']) {
								semusiCustomEvents.averageUserChunk.one_to_three += semusiCustomEvents.activeUserData[platform][app]['asl']['1-3'];
							}
							if (semusiCustomEvents.activeUserData[platform][app]['asl']['0:5-1']) {
								semusiCustomEvents.averageUserChunk.half_to_one += semusiCustomEvents.activeUserData[platform][app]['asl']['0:5-1'];
							}
							if (semusiCustomEvents.activeUserData[platform][app]['asl']['<30']) {
								semusiCustomEvents.averageUserChunk.less_than_thirtysec += semusiCustomEvents.activeUserData[platform][app]['asl']['<30'];
							}
						}
					}
				});
			}

			currentTotal = parseFloat((currentTotal / currentU)).toFixed(2);
			if (currentTotal >= 0) {
               var mins = parseInt(currentTotal / 60);
			   var seconds = parseInt(currentTotal - (mins * 60));
			   //Kotak Apps hack from UI (Data)
			//    if(0 < mins > 5){
            //        var mins = 3;
			//    }else if(5 < mins > 10){
            //        var mins = 8;
			//    }else if(10 < mins > 20){
            //        var mins = 7;
			//    }else if(20 < mins > 30){
			//    	   var mins = 7;
			//    }else if(30 < mins > 40){
			//    	   var mins = 9;
			//    }else if(40 < mins > 50){
			//    	   var mins = 8;
			//    }else if(50 < mins > 60){
			//    	   var mins = 7;	
			//    }else if(60 < mins > 100){
			//    	    var mins = 9;
			//    }else if(100 < mins > 150){
			//    	    var mins = 10;
			//    }else if(150 < mins > 200){
			//    	    var mins = 8;
			//    }else if(200 < mins > 250){
			//    	    var mins = 8;
			//    }else if(250 < mins > 300){
			//    	    var mins = 10;
			//    }else if(300 < mins > 350){
			//    	    var mins = 10;
			//    }else{
			//    	    var mins = 8;
			//    }
			   //Ends
				if (!isNaN(mins)) {
					$("#lblAvgSessionLength").text(mins);
				}
				if (!isNaN(seconds)) {
					$("#lblAvgSessionLengthSec").text(seconds);
				}

			}
			else {
				$("#lblAvgSessionLength").text(0);
				$("#lblAvgSessionLengthSec").text(0);
			}

			if (previousTotal > 0 && previousU > 0) {
				previousTotal = parseFloat((previousTotal / previousU)).toFixed(2);
				changedTotal = currentTotal - previousTotal;
				percentChange = (previousTotal == 0) ? 100 : parseFloat(changedTotal / previousTotal * 100).toFixed(2);
				var strPercentChange;
				var changeSign;
				if (percentChange > 0 && percentChange<200) {
					changeSign = '<div style="font-size:14px; color:#000;"><i class="fa fa-2x fa-caret-up"></i></div>'
					strPercentChange = parseInt(percentChange) + ' %';
				}else if(percentChange>200){
					changeSign = '<div style="font-size:14px; color:#000;"><i class="fa fa-2x fa-caret-up"></i></div>'
					strPercentChange = '10%';
				}
				else if (percentChange < 0) {
					percentChange = percentChange * -1;
					changeSign = '<div style="font-size:14px; color:#000;"><i class="fa fa-2x fa-caret-down"></i></div>';
					strPercentChange = parseInt(percentChange) + ' %';
				}
				else if (percentChange == 0) {
					changeSign = '';
					strPercentChange = parseInt(percentChange) + ' %';
				}
				if (previousTotal == 0) {
					changeSign = '';
					strPercentChange = 'NA';
				}
			}
			else {
				changeSign = '';
				strPercentChange = 'NA';
			}

			$("#tdSignSessionLength").html(changeSign);
			$("#lblChangeSessionLength").text(strPercentChange);
			tableData.push(["5+ mins", semusiCustomEvents.averageUserChunk.five_plus]);
			tableData.push(["3-5 mins", semusiCustomEvents.averageUserChunk.three_to_five]);
			tableData.push(["1-3 mins", semusiCustomEvents.averageUserChunk.one_to_three]);
			tableData.push(["0.5-1 mins", semusiCustomEvents.averageUserChunk.half_to_one]);
			tableData.push(["< 30 seconds", semusiCustomEvents.averageUserChunk.less_than_thirtysec]);

			$('#tblAvgLength > tbody >tr').remove();
			tableData.forEach(function (item) {
				$('#tblAvgLength > tbody').append('<tr ><td style="padding:3px;">' + item[0] + '</td><td style="padding:3px;text-align:right">' + item[1] + '</td></tr>');
			});
		}

         
		if($scope.avgSessionChart == true){  
		    let container = document.getElementById('averageSessionChart'); 
			while (container.firstChild) {
                container.removeChild(container.firstChild);
            }
            
			//Bar chart starts
			//preparing chart data
			let chartData = tableData.map(data =>{
				return {
					x: data[0] ,
					value: data[1],
					legendItem: {
						iconType: "circle",
					  }
				}
			});
				// create a chart
				var chart = anychart.pie(chartData);
				anychart.licenseKey("semusi.com-df30754a-aa10847e");
				var credits = chart.credits();
				credits.url("https://demo.appice.io/login");
				credits.logoSrc("https://demo.appice.io/assets/img/icon-title.png");
				credits.text("appICE");
	
				let legend = chart.legend();
				
			
				// enables legend
				legend.enabled(true);
				// set legend height
				chart.legend().paginator(false);

				legend.height(250);
				// set legend width
				legend.width(125);
				// set legend position
				legend.position("right");
				// set legend align
				legend.align("center");
				// legend items layout
				legend.itemsLayout("vertical");

				// create a bar series and set the data
				// var series = chart.column(chartData);

				// set the container id
				chart.container("averageSessionChart");

				// initiate drawing the chart
				chart.draw();
		 }


	}

	/*  number format function  like 10K, 5M etc ... */
    function nFormatter(num) {
        if (num >= 1000000000) {
           return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
        }
        if (num >= 1000000) {
           return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
        }
        if (num >= 1000) {
           return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
        }
        if (num == 0) {
            return 'NA';
        }
        return num;
    }


	function getActiveUserSessionStats(){
		var platform = $("#ddlPlatform").val();
		var dates = {
			startDate_C:semusiCommon.dateRange.currentStartDate,
			endDate_C:semusiCommon.dateRange.currentEndDate,
			startDate_P:semusiCommon.dateRange.previousStartDate,
			endDate_P:semusiCommon.dateRange.previousEndDate,
			startDate_CNew:semusiCommon.dateRange.currentStartDateNew,
			endDate_CNew:semusiCommon.dateRange.currentEndDateNew,
			startDate_PNew:semusiCommon.dateRange.previousStartDateNew,
			endDate_PNew:semusiCommon.dateRange.previousEndDateNew
		};

		var promise = appIceService.getActiveUserSessionStats(dates, platform);
		promise.then(function(data){
			$('#overlay').hide();
			if(data){
				semusiCustomEvents.activeUserData = data;
				$scope.populateActiveUsersChunk();
				$scope.populateAverageUsersChunk();
			}
		})
		.catch(function(){
			$('#overlay').hide();
		});

		/*	
		$.ajax({
			  type:"GET",
			  url:semusiCommon.API_PARTS.metrices.r + '/getActiveUserSessionStats',
			  data:{
				  args:JSON.stringify({
					  startDate_C:semusiCommon.dateRange.currentStartDate,
					  endDate_C:semusiCommon.dateRange.currentEndDate,
					  startDate_P:semusiCommon.dateRange.previousStartDate,
					  endDate_P:semusiCommon.dateRange.previousEndDate,
					  startDate_CNew:semusiCommon.dateRange.currentStartDateNew,
					  endDate_CNew:semusiCommon.dateRange.currentEndDateNew,
					  startDate_PNew:semusiCommon.dateRange.previousStartDateNew,
					  endDate_PNew:semusiCommon.dateRange.previousEndDateNew
				  }),
				  api_key: semusiGlobal.member.api_key,
				  app_id: semusiCommon.ACTIVE_APP_ID,
				  platform:platform
			  },
			  dataType:"jsonp",
			  success:function (data) {
				semusiCustomEvents.activeUserData= data;
				$scope.populateActiveUsersChunk();
				$scope.populateAverageUsersChunk();
			  }
		  });*/  
	}
  
	function getActiveUserTimelySessions(){

		var dates = {
			startDate_C:semusiCommon.addOffset(semusiCommon.dateRange.currentStartDate),
			endDate_C:semusiCommon.addOffset(semusiCommon.dateRange.currentEndDate),
			startDate_P:semusiCommon.addOffset(semusiCommon.dateRange.previousStartDate),
			endDate_P:semusiCommon.addOffset(semusiCommon.dateRange.previousEndDate),
			startDate_CNew:semusiCommon.dateRange.currentStartDateNew,
			endDate_CNew:semusiCommon.dateRange.currentEndDateNew,
			startDate_PNew:semusiCommon.dateRange.previousStartDateNew,
			endDate_PNew:semusiCommon.dateRange.previousEndDateNew
		};

		var promise = appIceService.getActiveUserTimelySessions(dates);
		promise.then(function(data){
			$('#overlay').hide();
			if(data){
				semusiCustomEvents.timelyCurrentData = data.current;
				semusiCustomEvents.timelyPreviousData = data.previous;
				$scope.populateTimelySessionsChunk();
			}
		})
		.catch(function(){
			$('#overlay').hide();
		});

		/*
		$.ajax({
			  type:"GET",
			  url:semusiCommon.API_PARTS.metrices.r + '/getActiveUserTimelySessions',
			  data:{
				  args:JSON.stringify({
					  startDate_C:semusiCommon.addOffset(semusiCommon.dateRange.currentStartDate),
					  endDate_C:semusiCommon.addOffset(semusiCommon.dateRange.currentEndDate),
					  startDate_P:semusiCommon.addOffset(semusiCommon.dateRange.previousStartDate),
					  endDate_P:semusiCommon.addOffset(semusiCommon.dateRange.previousEndDate),
					  startDate_CNew:semusiCommon.dateRange.currentStartDateNew,
					  endDate_CNew:semusiCommon.dateRange.currentEndDateNew,
					  startDate_PNew:semusiCommon.dateRange.previousStartDateNew,
					  endDate_PNew:semusiCommon.dateRange.previousEndDateNew
				  }),
				  api_key: semusiGlobal.member.api_key,
				  app_id: semusiCommon.ACTIVE_APP_ID
			  },
			  dataType:"jsonp",
			  success:function (data) {
				semusiCustomEvents.timelyCurrentData = data.current;
				semusiCustomEvents.timelyPreviousData = data.previous;
				$scope.populateTimelySessionsChunk();
			  }
		  });  */
	}

	semusiCommon.setDateRange(null,null);
	$scope.initDateRange();

	$('.platform-select').on('click',function(){
        var data = $(this).attr('data-attr');
        if(data == 'all'){
            $('#platform').text('All');
        }else if(data == 'android'){
            $('#platform').text('Android');
        }else if(data == 'ios'){
            $('#platform').text('iOS');
		}else if(data == 'web'){
            $('#platform').text('Web');
        }
        $("#ddlPlatform").val(data)
        $("#ddlPlatform").val();
        $scope.populateActiveUsersChunk();
        $scope.populateAverageUsersChunk();
        $scope.populateTimelySessionsChunk();
   });
	$('#platform').text('All');
});