appice.controller('eventsController', function ($scope, appIceService, $routeParams, $location) {
	var topEventChart;
	var attributeEventChart;
	var semusiCustomEvents = {}
	$scope.eventList = [];
	$scope.events = [];
	semusiCustomEvents.customEvents = [];
	$scope.drillDown = false;
 	$scope.message = '';
 	$scope.topGraphEvents = [];
 	$scope.bottomGraphEvents = [];
 	$scope.stackedLabels=[];
 	var newGraphLabel;
 	$scope.datasets = [];
 	$scope.labels =[];
 	$scope.isTop = false;
	 $scope.initDataset =[];
	 $scope.tabArray = [];
	 $scope.AllEventList =[]
	 $scope.journey={}
	 $scope.journey.events = [{}];
	 $scope.eventListData = [];
	 $scope.journeyKey = false;

 	//Graph management
  function buildGraph(datasets,labels,isTop){
	  	datasets = _.sortBy(datasets, 'label');
	        var barData = {
	          labels :labels,
	          datasets:datasets
	        };

					//New Chart object in Array

					var chartObj= {
								type: 'bar',
								data: barData,
								options: {
									    legend: {
								            display: false
								        },
										scales: {
												xAxes: [{
															stacked: true,
															gridLines: {
																	display:false
															},
															scaleLabel: {
																display: true,
																labelString: 'Date'
															}
													}],
													yAxes: [{
														stacked: true,
															gridLines: {
																	display:false
															},
															scaleLabel: {
																display: true,
																labelString: 'Event Count'
															}
													}]
										}
								}
						}

					// handleGenerateGraph();
					if(isTop){
						// if(datasets.length==0){
						// 	$scope.topGraphEvents =[];
						// }else{
      //                       $scope.topGraphEvents = $scope.stackedLabels;
						// }
						if(topEventChart!== undefined){
			                // topEventChart.clear();
			                topEventChart.destroy();
			            }
						topEventChart = new Chart(document.getElementById("topEventsChart").getContext("2d"), chartObj);
						let canvas = document.getElementById("topEventsChart");
						canvas.onclick = function (evt){
							var activePoint = topEventChart.getElementAtEvent(evt)[0];
   							var data = activePoint._chart.data;
							var datasetIndex = activePoint._datasetIndex;
							 //showing all data of selected date
							
							var dataArray = [];
							for(let ele of data.datasets){
								dataArray.push({"event":ele.label,"count":ele.data[activePoint._index]});
							}
							$scope.tabArray = dataArray
							$scope.buildEventsTable($scope.tabArray);
							$('#myModal').modal('toggle');
						}
						
						
					}
					else{
						// if(datasets.length==0){
						// 	$scope.bottomGraphEvents =[];
						// }else{

						// $scope.bottomGraphEvents = $scope.stackedLabels;
						// }
						if(attributeEventChart!== undefined){
										// attributeEventChart.clear();
										attributeEventChart.destroy();
						}
						attributeEventChart = new Chart(document.getElementById("eventAttributeChart").getContext("2d"), chartObj);
						let canvas = document.getElementById("eventAttributeChart");
						canvas.onclick = function(evt){
							var activePoint = attributeEventChart.getElementAtEvent(evt)[0];
   							var data = activePoint._chart.data;
							var datasetIndex = activePoint._datasetIndex;
							 //showing all data of selected date
							
							var dataArray = [];
							for(let ele of data.datasets){
								dataArray.push({"event":ele.label,"count":ele.data[activePoint._index]});
							}
							$scope.tabArray = dataArray
							$scope.buildEventsAttributeTable($scope.tabArray);
							$('#myattrModal').modal('toggle');
						    
						}
					}
  }



	function init() {
				// TODO  CURRENTLY DONE FOR YONO TB HANDLED LATER
				$("#p1").show();
				$("#advance-daterange").show();
		$scope.selectedEvent = "Select Event";
		$scope.selectedEventAttribute = "Select Attribute";
		$scope.selectedJourneyType = "Select a Journey";
		$scope.selectedCEventAttribute = "Select Attribute";
		$scope.isCEventAttribute = false;
		$scope.cList = [];
		$scope.eventAttributeList = [];

		semusiCommon.setDateRange(null, null);
		getEventList();
		getEventsStats();
		var date = new Date();
		var currentMonth = date.getMonth();
		var currentDate = date.getDate();
		var currentYear = date.getFullYear();

		$('#advance-daterange span').html(moment().subtract('days', 29).format(semusiCommon.getDateFormatt()) + ' - ' + moment().format(semusiCommon.getDateFormatt()));

		$('#advance-daterange').daterangepicker({
			format: semusiCommon.getDateFormatt(),
			startDate: moment().subtract(29, 'days'),
			endDate: moment(),
			minDate: new Date(currentYear, currentMonth-3, currentDate),
			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();
			getEventList();
			getEventsStats();

			//**
			// * @description get event getEventAttributeStats() api gets called
			// **/
			var eventAttribute = $scope.selectedEventAttribute ? $scope.selectedEventAttribute : null
			$scope.showAttributeStats(eventAttribute) ;
			$scope.showCAttributeStats(eventAttribute); // for custom events

		});

    $("#downloadLink").click(function(){
      if($("#ddlEventList").val() == null){
       alert('Please select an event');
        return false;
      }else{
        var args = {filter:{}};
        var dateRange = {sd:semusiCommon.dateRange.currentStartDate,ed:semusiCommon.dateRange.currentEndDate};
        args.filter.dateRange = dateRange;
        args.filter.dateRange.dates = [];
        var startDate =args.filter.dateRange.sd*1000;
        while(startDate < args.filter.dateRange.ed*1000 ){
            args.filter.dateRange.dates.push(moment(startDate).format('YYYY-MM-DD'));
            startDate = parseInt(moment(startDate).add(1,'days').valueOf());
        }

        args.filter.platform = $('#ddlPlatform').val();
        if($("#ddlEventList option:not(:selected)").length==0 && $("#ddlEventList option:selected").length>0){
            //All
            args.filter.selectAll = true;
						args.filter.events = $("#ddlEventList").val();
        }
        //else if($("#ddlEventList option:not(:selected)").length>0 && $("#ddlEventList option:selected").length>0){
				else if($("#ddlEventList option:not(:selected)").length>0 && $("#ddlEventList option:selected").length>0){
           //Selected ones
           args.filter.selectAll = false;
           args.filter.events = $("#ddlEventList").val();
        }
        else if($("#ddlEventList option:not(:selected)").length == 0 && $("#ddlEventList option:selected").length == 0){
            //No event is selcted
            alert("None of the events is selected.");
            return;
        }

				// select segments
				var eventsSegments = [];
				if(args.filter.events){
						$scope.eventList.forEach(function(evt){
								if(args.filter.events.indexOf(evt.event) >= 0){
										evt.list.forEach(function(segment){
												if(segment.type === "string"){
													eventsSegments.push(segment.name);
												}
										});
								}
						})
						args.filter.eventsSegments = eventsSegments;
				}

				var filename = "events"+dateRange.sd+"-"+dateRange.ed+".csv";
				window.location.href = appiceEncode.encodePayload(semusiCommon.API_PARTS.metrices.r + '/downloadEventsStats?api_key='+ semusiCommon.getActiveUser.api_key+'&app_id='+ semusiCommon.ACTIVE_APP_ID+'&offset='+semusiCommon.getOffset()+ '&uniqueNumber=' +semusiCommon.randomNumber()+'&args='+JSON.stringify(args)+'&filename='+filename);
				$scope.showPopup('Event CSV', '' , 'success')

			}

	});
	
	$("#attrdownloadLink").click($scope.downloadEventAttribute);

	}

	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';
		}
		return num;
		}

	/**
	 * @description: TableBuilder for EventChart
	 */
	$scope.buildEventsTable = function(dataArray){
		if(dataArray.length > 0){
			dataArray = dataArray.filter(ele=>{
				return ele.count!==0;
			});
			dataArray.sort((a,b)=>{
				return b.count-a.count;
			});
			 
		    dataArray.forEach(ele=>{
				ele.count = nFormatter(ele.count);
			});
			$("#event-tbody").empty();
		}
		 
			for(list of dataArray){
				let tabContent  =  
			  `
				  <tr>
					<td>${list.event}</td>
					<td>${list.count}</td>
				  </tr>`
			document.getElementById("event-tbody").insertAdjacentHTML("beforeend",tabContent); 
		  }			  
		}

								// SELECTING/UNSELECTING ALL CHECKBOXES

	$("#toggle_chk").on('change', function () {
		
		var allTable = document.getElementById("attrTable"); 	//getting the table of atrribures
		var items = allTable.getElementsByClassName("checkitem");

		for (var i = 0; i < items.length; i++) {
			items[i].checked = $("#toggle_chk").is(':checked');

		}
	});

					// OPENING POPUP FOR DOWNLOADING ATTRIBUTES
	$("#popupBtn").click(function () {
		var selectedEvent = $scope.selectedEvent;
		var selectedEventAttribute = $scope.selectedEventAttribute;
		if(selectedEvent === 'Select Event' || selectedEvent === undefined || selectedEvent === null){
			alert("Please select an event"); 		//IF NO EVENT IS SELECTED 
			return;
		}
		else if(selectedEventAttribute === 'Select Attribute' || selectedEventAttribute === undefined || selectedEventAttribute === null){
			if ($scope.eventAttributeList.length == 0) {
				//INCASE THE SELECTED EVENT ATTRIBUTE HAS NO ATTRIBUTE
				$('#noattrwarning').modal('show');

			} else {
				//IN CASE USER HAS NOT SELECTED ATTRIBUTE
				alert("Please select an attribute");
				return;
			}
		} else {
			 
			// POPUP IF EVENT IS SELECTED 
			$('#modalDownloadPopup').modal('show');

		}
	});

		// GETTIING SELECTED ATTRIBUTES FUNCTION CALLEDFROM DOWNLOAD EVENT ATTRIBUTE

	function getSelected() {

		var selected = [];
		var allTable = document.getElementById("ddlEventattrList"); 	//getting the table of atrribures
		var items = allTable.getElementsByTagName("INPUT"); 			// All EVENT ATTRIBUTES

		for (var i = 0; i < items.length; i++) {
			if (items[i].checked) {
				selected.push(items[i].value);
			}
		}
		return selected;

	}
	/**
     * @description Download EventAttribute File
     */
	$scope.downloadEventAttribute = function(){

		var selectedEvent = $scope.selectedEvent;
		var selectedEventAttribute = getSelected();

		if (selectedEventAttribute.length == 0) {

			//IN CASE USER HAS NOT SELECTED ATTRIBUTE in DOWNLOAD popup
			alert("Please select an attribute to download");
			return;
		}
			
		let args = {filter:{}};
		args.filter.eventName = selectedEvent;
		args.filter.attributeName = selectedEventAttribute;
		let dateRange = {sd:semusiCommon.dateRange.currentStartDate,ed:semusiCommon.dateRange.currentEndDate};
        args.filter.dateRange = dateRange;
        args.filter.dateRange.dates = [];
        let startDate =args.filter.dateRange.sd*1000;
        while(startDate < args.filter.dateRange.ed*1000 ){
            args.filter.dateRange.dates.push(moment(startDate).format('YYYY-MM-DD'));
            startDate = parseInt(moment(startDate).add(1,'days').valueOf());
        }

		args.filter.dateRange.ed = semusiCommon.addOffset(args.filter.dateRange.ed);
		args.filter.platform = $('#ddlPlatform').val();
		let filename = "eventsAttribute"+dateRange.sd+"-"+dateRange.ed+".csv";

		window.location.href = appiceEncode.encodePayload(semusiCommon.API_PARTS.metrices.r + '/downloadEventsAttributeStats?api_key='+ semusiCommon.getActiveUser.api_key+'&app_id='+ semusiCommon.ACTIVE_APP_ID+'&offset='+semusiCommon.getOffset()+ '&uniqueNumber=' +semusiCommon.randomNumber()+'&args='+JSON.stringify(args)+'&filename='+filename);
		$scope.showPopup('EventAttribute CSV', '' , 'success');

	}
//  END Download EventAttribute File

	// show popup box
	$scope.showPopup = function(title, msg, type){
			// show popup box
			swal({
					title: title,
					text: msg,
					type: type, //"error"
					// showCancelButton: !0,
					// confirmButtonClass: "btn-"+type,
					// confirmButtonText: "Close"
			});
	}

	/**
	 * @description: TableBuilder for eventAttribute Chart
	 */
	$scope.buildEventsAttributeTable = function(dataArray){

		if(dataArray.length > 0){
			dataArray = dataArray.filter(ele=>{
				return ele.count!==0;
			});
			dataArray.sort((a,b)=>{
				return b.count-a.count;
			});
			 
		    dataArray.forEach(ele=>{
				ele.count = nFormatter(ele.count);
			})
		 	
			$("#eventattr-tbody").empty();
		}
			for(list of dataArray){
				let tabContent  =  
			  `   <tr>
					<td>${list.event}</td>
					<td>${list.count}</td>
				  </tr>
				`
		document.getElementById("eventattr-tbody").insertAdjacentHTML("beforeend",tabContent); 
	  }
	}




	//handleEventAttributeGraph();

		$('.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)

			$('.ms-drop').find("ul").remove();
			getEventList();
			getEventsStats();

	});

	$('#platform').text('All');


	function getEventList() {
		$scope.eventList = [];
		var promise = appIceService.getEventList();
		promise.then(function (eventsData) {
			if (eventsData.data != undefined) {
				var events = eventsData.data;
				let journeys = [];
				var len = $scope.journey.events.length;
				if($scope.journey.events[len-1]?.selectedJourney == undefined || $scope.journey.events[len-1]?.selectedJourney == '' ){
					$scope.eventListData[len-1] = events;
				   }
				events.forEach(function(event){
					if(event.journey){
						journeys.push(event.journey)
						$scope.journeyKey = true;
					}
				})

				const journeyArray = journeys.filter((elem, index, self) => {
					return index === self.indexOf(elem);
				});
				$scope.journeysArray = journeyArray;
				$scope.cList = eventsData.clist;
				events.forEach(function (item) {
					if (item.event != '_App_Stop' && item.event != '_App_Start' && item.event != 'Session_Start' && item.event != 'Session_End' && item.event != 'App_Foreground' && item.event != 'App_Background') {
						$scope.eventList.push({ event: item.event, list: item.list , journey:(item.journey) ? item.journey: undefined });
					}
				});
			}
			else if (eventsData.data == undefined) {
				$scope.message = 'There is no event';
			}
			$scope.eventList = _.sortBy($scope.eventList, 'event');
			$scope.AllEventList =	$scope.eventList
		});
	}

	$scope.onJourneySelect = function (e) {

		$scope.eventList =	$scope.AllEventList 
		var length = $scope.journey.events.length;
		var selectedOption = e;
		const selectedJourney = selectedOption.replace(/string:/, "");
	  

		$scope.eventListData[length - 1] = [];
		for (let i = 0, len = $scope.eventList.length; i < len; i++) {
		  if ( typeof $scope.eventList[i] === "object" && $scope.eventList[i].journey !== undefined ) {
			if ($scope.eventList[i].journey === selectedJourney) {
				console.log("PUSHED")
			  $scope.eventListData[length - 1].push($scope.eventList[i]);
			}
		  }
		}
		$scope.eventList =  $scope.eventListData[length - 1]
		
	  };
	  
	function getEventsStats() {
		semusiCustomEvents.customEvents = [];

		var dates = {
			startDate:semusiCommon.dateRange.currentStartDate,
			endDate:semusiCommon.dateRange.currentEndDate,
			startDateNew:semusiCommon.dateRange.currentStartDateNew,
			endDateNew:semusiCommon.dateRange.currentEndDateNew
		};

		var promise = appIceService.getEventsStats(dates);
		promise.then(function (data) {
			$('#overlay').hide();
			if (data.length > 0) {
				$scope.drillDown = true;
				semusiCustomEvents.customEvents = data;
				createBarChartData(true);
			}
			else {
				// remove top chart
				$("#ddlEventList").multipleSelect("setSelects", []);
				if (topEventChart !== undefined) {
					// topEventChart.clear();
					topEventChart.destroy();
				}

				// remove bottom chart
				$scope.drillDown = false;
				if(attributeEventChart!== undefined){
							// attributeEventChart.clear();
							attributeEventChart.destroy();
				}
			}
		})
		.catch(function(){
			$('#overlay').hide();
		});
	}
	generateRandomFloat = function (){
        const array = new Uint16Array(10);
        self.crypto.getRandomValues(array);
  
              for (const num of array) {
            var length = num.toString().length
              
            if(length==1){
              return num/10;
            }
            if(length==2){
              return num/100;
            }
            if(length==3){
              return num/1000;
            }
            if(length==4){
              return num/10000;
            }
            if(length==5){
              return num/100000;
            }
              };
       return 
  }
	function getRandomColor() {
		var letters = '0123456789ABCDEF'.split('');
		var color = '#';
		for (var i = 0; i < 6; i++) {
			color += letters[Math.floor(generateRandomFloat() * 16)];
		}

		return color;
	}

	function createBarChartData(isTop){
			$scope.datasets = [];

			if (semusiCustomEvents.customEvents != undefined && semusiCustomEvents.customEvents != '' && isTop) {
				var labels = [];
				var stackedLabels = [];
				if (semusiCustomEvents.customEvents != null && semusiCustomEvents.customEvents.length > 0) {
					var data = {
						"android": {},
						"ios": {},
						"web": {}
					};
					semusiCustomEvents.customEvents.forEach(function (item) {
						if (item.android) {
							data['android'] = _.extend(data['android'], item.android);
						}
						if (item.ios) {
							data['ios'] = _.extend(data['ios'], item.ios);
						}
						if (item.web) {
							data['web'] = _.extend(data['web'], item.web);
						}
					});

					var platform = $("#ddlPlatform").val();
					if (platform == "all") {
						if (data['android']) {
							labels = labels.concat(Object.keys(data['android']));
						}
						if (data['ios']) {
							labels = labels.concat(Object.keys(data['ios']));
						}
						if (data['web']) {
							labels = labels.concat(Object.keys(data['web']));
						}
						labels = _.union(labels);
					}
					else {
						if (data[platform]) {
							labels = Object.keys(data[platform]);
						}

					}

					labels = _.sortBy(labels, function (o) {
						var datestr = o.replace(/\_/g, "/");
						return (new Date(datestr));
					});
					if (platform == "all") {
						labels.forEach(function (value) {
							if (data['android'] && data['android'][value]) {
								stackedLabels = stackedLabels.concat(Object.keys(data['android'][value]));
							}
							if (data['ios'] && data['ios'][value]) {
								stackedLabels = stackedLabels.concat(Object.keys(data['ios'][value]));
							}
							if (data['web'] && data['web'][value]) {
								stackedLabels = stackedLabels.concat(Object.keys(data['web'][value]));
							}
						});
					}
					else {
						labels.forEach(function (value) {
							stackedLabels = stackedLabels.concat(Object.keys(data[platform][value]));
						});
					}
				}

				stackedLabels = _.union(stackedLabels);
				var optionList = [];
				var html = '';

				stackedLabels = _.sortBy(stackedLabels);
				stackedLabels.forEach(function (v, key) {
					if (v != 'total' && v != 'Campaign_Viewed' && v != 'Campaign_Clicked'
						&& v != 'Campaign_Received' && v != 'Campaign_Deleted') {

						html += '<option value="' + v + '">' + v + '</option>';
						if (v != '_App_Stop' && v != '_App_Start' && v != 'Session_Start' && v != 'Session_End' && v != 'App_Foreground' && v != 'App_Background') {
							optionList.push(v);
						}
					}
				});

				optionList = _.sortBy(optionList);
				$('#ddlEventList').html('');
				$('#ddlEventList').html(html);
				$('#ddlEventList').multipleSelect();
				$("#ddlEventList").multipleSelect("setSelects", optionList);
			}

        var labels = [];
        var datasets = [];
		var labelsChart = [];
        if(semusiCustomEvents.customEvents!=null && semusiCustomEvents.customEvents.length>0){
          var data = {
              "android":{},
							"ios":{},
							"web": {}
          };

          semusiCustomEvents.customEvents.forEach(function(item){
              if(item.android){
                  data['android'] = _.extend(data['android'],item.android);
              }
              if(item.ios){
                  data['ios'] = _.extend(data['ios'],item.ios);
							}
							if(item.web){
								data['web'] = _.extend(data['web'],item.web);
						}
          });

            var platform = $("#ddlPlatform").val();
            if(platform=="all"){
              if(data['android']){
                labels = labels.concat(Object.keys(data['android']));
              }
              if(data['ios']){
                labels = labels.concat(Object.keys(data['ios']));
							}
							if(data['web']){
                labels = labels.concat(Object.keys(data['web']));
              }
              labels = _.union(labels);
            }
            else{
              if(data[platform]){
                labels = Object.keys(data[platform]);
              }

            }
          var stackedLabels=[];
          labels = _.sortBy(labels, function(o) {
                    var datestr = o.replace(/\_/g, "/");
                    return (new Date(datestr));
                });

          ///Check Labels To remove at the right side of Event Graph
    //       if(labels.length==0){
				// $scope.stackedLabels.push();       
				// }
          if(platform=="all"){
            labels.forEach(function(value){
              if(data['android'] && data['android'][value]){
                stackedLabels = stackedLabels.concat(Object.keys(data['android'][value]));
              }
              if(data['ios'] && data['ios'][value]){
                stackedLabels = stackedLabels.concat(Object.keys(data['ios'][value]));
							}
							if(data['web'] && data['web'][value]){
                stackedLabels = stackedLabels.concat(Object.keys(data['web'][value]));
              }
			  let d = value.split("_");
			  labelsChart.push((d[1]+"-"+d[2]+"-"+d[0]));
            });
          }
          else{
            labels.forEach(function(value){
              if(platform=="android"){
                if(topEventChart!== undefined){
                  // topEventChart.clear();
                  topEventChart.destroy();
                }
                stackedLabels = stackedLabels.concat(Object.keys(data['android'][value]));
              }
              else if(platform=="ios"){
                if(topEventChart!== undefined){
                  // topEventChart.clear();
                  topEventChart.destroy();
                }
                stackedLabels = stackedLabels.concat(Object.keys(data['ios'][value]));
							}
							else if(platform=="web"){
                if(topEventChart!== undefined){
                  // topEventChart.clear();
                  topEventChart.destroy();
                }
                stackedLabels = stackedLabels.concat(Object.keys(data['web'][value]));
              }
			  let d = value.split("_");
			  labelsChart.push((d[1]+"-"+d[2]+"-"+d[0]));
            });
          }

					stackedLabels = _.union(stackedLabels);
					// stackedLabels=destackedLabels.slice(1,12);
					//$scope.stackedLabels=[];
          var index=0;
          stackedLabels.forEach(function(stLable){
            if(stLable != '_App_Stop' && stLable != '_App_Start' && stLable != 'Session_Start'
              && stLable != 'Session_End' && stLable != 'App_Foreground' && stLable != 'App_Background'
              && stLable != 'total' && stLable != 'Campaign_Viewed' && stLable != 'Campaign_Clicked'
                          && stLable != 'Campaign_Received' && stLable != 'Campaign_Deleted'){

              if(stLable == 'watch'){
                stLable = "watchs";
							}
              var bar = {};
              if(index>11){
                bar.backgroundColor = getRandomColor();
                bar.borderColor = getRandomColor();
                bar.borderWidth = 1;
              }
              else{
                bar.backgroundColor = semusiCommon.basicColors[index];
                bar.borderColor = semusiCommon.basicColors[index];
                bar.borderWidth = 1;
							}
							bar.label=stLable.replace(/\:/g, ".");
							// Angular UI use
							// var stackListObj = {}							
							// stackListObj.backgroundColor = bar.backgroundColor;
							// stackListObj.borderColor=bar.borderColor;
							// stackListObj.label = stLable;
							// stackListObj.value = 0;

							bar.data=[];
              labels.forEach(function(label){
                var lblValue = 0;
                if(platform=="all" && data['android'] && data['android'][label] && data['android'][label][stLable]){
                  lblValue+=data['android'][label][stLable];
                }
                if(platform=="all" && data['ios'] && data['ios'][label] && data['ios'][label][stLable]){
                  lblValue+=data['ios'][label][stLable];
								}
								if(platform=="all" && data['web'] && data['web'][label] && data['web'][label][stLable]){
                  lblValue+=data['web'][label][stLable];
                }
                if(platform!="all"){
                  if(data[platform] && data[platform][label] && data[platform][label][stLable]){
                    lblValue+=data[platform][label][stLable];
                  }
                }
                if(stLable == '_app_crash' && platform=="all" && data['android'] && data['android'][label] && data['android'][label][stLable]){
                      if(data['android'][label][stLable] == undefined || data['android'][label][stLable] == null || data['android'][label][stLable] == ''){
                        lblValue = 0;
                      }else{
                        lblValue+=data['android'][label][stLable];
                      }
                      bar.label = stLable.replace(/\:/g, "."),
                      bar.type = 'line',
                      bar.fill = false,
                      bar.borderColor = '#ff0000',
                      bar.backgroundColor = '#ff0000',
                      bar.pointBorderColor = '#ff0000',
                      bar.pointBackgroundColor = '#ff0000',
                      bar.pointHoverBackgroundColor = '#ff0000',
                      bar.pointHoverBorderColor = '#ff0000'
                    }
                    if(stLable == '_app_crash' &&  platform=="all" && data['ios'] && data['ios'][label] && data['ios'][label][stLable]){
                      if(data['ios'][label][stLable] == undefined || data['ios'][label][stLable] == null || data['ios'][label][stLable] == ''){
                        lblValue = 0;
                      }else{
                        lblValue+=data['ios'][label][stLable];
                      }
                      bar.label = stLable.replace(/\:/g, "."),
                      bar.type = 'line',
                      bar.fill = false,
                      bar.borderColor = '#ff0000',
                      bar.backgroundColor = '#ff0000',
                      bar.pointBorderColor = '#ff0000',
                      bar.pointBackgroundColor = '#ff0000',
                      bar.pointHoverBackgroundColor = '#ff0000',
                      bar.pointHoverBorderColor = '#ff0000'
										}
										if(stLable == '_app_crash' &&  platform=="all" && data['web'] && data['web'][label] && data['web'][label][stLable]){
                      if(data['web'][label][stLable] == undefined || data['web'][label][stLable] == null || data['web'][label][stLable] == ''){
                        lblValue = 0;
                      }else{
                        lblValue+=data['web'][label][stLable];
                      }
                      bar.label = stLable.replace(/\:/g, "."),
                      bar.type = 'line',
                      bar.fill = false,
                      bar.borderColor = '#ff0000',
                      bar.backgroundColor = '#ff0000',
                      bar.pointBorderColor = '#ff0000',
                      bar.pointBackgroundColor = '#ff0000',
                      bar.pointHoverBackgroundColor = '#ff0000',
                      bar.pointHoverBorderColor = '#ff0000'
                    }
                    if(platform !='all' && stLable == '_app_crash'){
                      if(data[platform][label][stLable] == undefined || data[platform][label][stLable] == null || data[platform][label][stLable] == ''){
                        lblValue = 0;
                      }else if(data[platform] && data[platform][label] && data[platform][label][stLable]){
                        lblValue+=data[platform][label][stLable];
											}
                      bar.label = stLable.replace(/\:/g, "."),
                      bar.type = 'line',
                      bar.fill = false,
                      bar.borderColor = '#ff0000',
                      bar.backgroundColor = '#ff0000',
                      bar.pointBorderColor = '#ff0000',
                      bar.pointBackgroundColor = '#ff0000',
                      bar.pointHoverBackgroundColor = '#ff0000',
                      bar.pointHoverBorderColor = '#ff0000'
										}
									
                    //if(lblValue != 0){
                    bar.data.push(lblValue);
										//stackListObj.value += lblValue;
							});
					        //stackListObj.selected=false;       
							// Angular UI use
							// if(platform==="ios"){
              //     $scope.stackedLabels.push();
							// }else{
              //     $scope.stackedLabels.push(stackListObj);
							// }
							// if(datasets.length < 10 && isTop===true){
							// 	datasets.push(bar);
							// 	stackListObj.selected=true; 
							// }else if(isTop===false){
							//     datasets.push(bar);
							// 	stackListObj.selected=true;
							// }
							datasets.push(bar);
              index++;
            }
          });

        }
					 
				let newDatasets = [];
				if(isTop){
					$scope.topGraphEvents = datasets.reduce((list, item) =>{
						item.selected = false;
						item.value = item.data.reduce((count, elem) => count += elem, 0);
						if(list.length < 10){
							item.selected = true;
							newDatasets.push(item);
						}
						list.push(item);
						return list;
					}, []);							
				}
				else {
					$scope.bottomGraphEvents = datasets.reduce((list, item) =>{
							item.selected = false;
							item.value = item.data.reduce((count, elem) => count += elem, 0);
							if(list.length < 10){
								item.selected = true;
								newDatasets.push(item);
							}
							list.push(item);
							return list;
					}, []);
				}

				 // Graph Rendering Through DataSets that we Prepare
				 $scope.labels = labelsChart;
				 $scope.isTop = isTop;
				 $scope.datasets = newDatasets;
				 if($scope.datasets.length==0){
					 $scope.initDataset =[];
				 }else{
					 $scope.initDataset = $scope.datasets[0].data;
				 }
				
				function formatDates(dateStrings, format) {
					return dateStrings.map(dateString => {
						const dateParts = dateString.split('-');
						const year = dateParts[2];
						const month = dateParts[0];
						const day = dateParts[1];
						const date = new Date(year, month - 1, day); // Month is 0-based
						
						const formatter = new Intl.DateTimeFormat('en-US', {
							year: 'numeric',
							month: 'short',
							day: 'numeric'
						});
						
						return formatter.format(date);
					});
				}
				const formattedDates = formatDates(labelsChart, semusiCommon.getDateFormatt());
				 buildGraph(newDatasets,formattedDates,isTop);
  }


  //Onclick Function for Event Filter

  $scope.selectedSpecificEvent=function(stack){
		stack.selected = (stack.selected)? false : true;
		if(stack.selected){
			$scope.datasets.push(stack);
		}
		else {
				let elemIndex = $scope.datasets.findIndex((d, index)=>{
						 
						if(d.label == stack.label){
							return index+1;
						}
				});
				$scope.datasets.splice(elemIndex,1); 
		}
	$scope.isTop=true;
  	buildGraph($scope.datasets, $scope.labels, $scope.isTop);
  	  
  }


  //Onclick Function For Event Attribute Filter

  $scope.selectedSpecificEventAttribute=function(stack){
		
		stack.selected = (stack.selected)? false : true;
		if(stack.selected){
			$scope.datasets.push(stack);
		}
		else {
				let elemIndex = $scope.datasets.findIndex((d, index)=>{
						 
						if(d.label == stack.label){
							return index+1;
						}
				});
				$scope.datasets.splice(elemIndex,1); 
		}

  	$scope.isTop=false;
  	buildGraph($scope.datasets,$scope.labels,$scope.isTop); 
   }



  	$scope.populateEventAttributes = function (eventname) {
		var data = [];
		var data1 = [];
		var data2 = [];
		var html;
		if ($('#swiu1').text() == 'Select Attribute') {

		} else {
			$('#swiu1').text('Select Attribute')
		}

		$scope.selectedEvent = eventname;
		$scope.eventList.forEach(function (item) {
			if (item.event == eventname) {
				$scope.eventAttributeList = item.list;
				$scope.eventAttributeList = _.sortBy($scope.eventAttributeList, 'name');
				if ($scope.eventAttributeList.length == 0) {
					$('#noAttrs').show();
					$scope.selectedEventAttribute = 'Select Attribute'; //UPDATING THE EVENT ATTRIBUTE 
				} else {
					$('#noAttrs').hide();
				}

				data = item.list;

				data.forEach(dt => {
					data1.push(dt.name)
				})

				// hide city attributes
				$scope.selectedCEventAttribute = "Select Attribute";
				$scope.isCEventAttribute = false;
				$('#swiu2').text("Select Attribute");
			}
		});

		data1.forEach(function (v, key) {
			html += '<tr><td><input type="checkbox" class="checkitem" onclick="selectallCheck()" value="' + v + '" />&nbsp;'
			html += '&nbsp;&nbsp;&nbsp;<label>' + v + '</label></td></tr>'

			data2.push(v);

		});
		data2 = _.sortBy(data2);
		$('#ddlEventattrList').html('');
		$('#ddlEventattrList').html(html);

		if(attributeEventChart!== undefined){
			// attributeEventChart.clear();
			attributeEventChart.destroy();
		}
	}


	$scope.showAttributeStats = function (attValue) {
		if(attributeEventChart!== undefined){
				// attributeEventChart.clear();
				attributeEventChart.destroy();
		}

		$('#swiu1').text(attValue)
		$scope.selectedEventAttribute = attValue;
		var promise = appIceService.getEventAttributeStats($scope.selectedEvent, $scope.selectedEventAttribute);
		promise.then(function (stats) {
			semusiCustomEvents.customEvents = stats;
			if (stats.length > 0) {
				createBarChartData(false);
			}

			if (attValue == 'City' && $scope.cList.length > 0) {
				$scope.cList = _.sortBy($scope.cList, 'name');
				$scope.isCEventAttribute = true;
			}
			else {
				$scope.selectedCEventAttribute = "Select Attribute";
				$scope.isCEventAttribute = false;
				$('#swiu2').text("Select Attribute")
			}
		});
	}

	$scope.showCAttributeStats = function (attValue) {
		if(attributeEventChart!== undefined){
						// attributeEventChart.clear();
						attributeEventChart.destroy();
		}

		$('#swiu2').text(attValue)
		$scope.selectedCEventAttribute = attValue;
		var promise = appIceService.getEventAttributeStats($scope.selectedEventAttribute, $scope.selectedCEventAttribute);
		promise.then(function (stats) {
			semusiCustomEvents.customEvents = stats;
			if (stats.length > 0) {
				createBarChartData(false);
			}
		});
	}

	init();
});


	// UNSELECTING/SELECTING THE SELECTALL BUTTON WHILE SELECTING ATTRIBUTES

function selectallCheck (){
		
		if ($(".checkitem").length == $(".checkitem:checked").length) {
			$("#toggle_chk").prop("checked", true);
		} else {
			$("#toggle_chk").prop("checked", false);
		}

	}
