appice.controller("funnelsViewController", function(
  $scope,
  $rootScope,
  appIceService,
  $routeParams,
  $location
) {
  init();
  var graph;
  function init() {
    $("#p1").hide();
    $("#advance-daterange").hide();
    $scope._id = $routeParams.id;
    $scope.height = 300;
    $scope.objectId = objectId();
    $scope.funnelStats = [];
    $scope.selectedAttribute = [];
    $scope.filteredSelectedAttribute = [];
    $scope.sortBy = 'DESC';
    $scope.actorProperty = "did";
    $scope.haveDone = [];
    $scope.haveNotDone = [];
    $scope.attrArray = []
    $scope.filteredAttributes = [];
    // funnel export enable for active app id
    
    //if(semusiCommon.FEAPPS == semusiCommon.ACTIVE_APP_ID){    funnel download allow for all apps
      $scope.FEAPPS = true;
    //}
    $scope.audObj = {
      segmentinfo: {
        who: [],
        what: [],
        where: [],
        when: []
      }
    };

    $scope.funnelShowBy = [
      {
        key: "did",
        name: "Users"
      },
      {
        key: "sid",
        name: "Session"
      }
    ];
    $scope.funnel = "";
    getFunnels();

    $("#funnel_drop").hide();
    $("#page-loader").show();
  }

  function getFunnels() {
    promise = appIceService.getEventFunnels();
    promise.then(function(funnels) {
      $("#page-loader").hide();
      $("#overlay").hide();
      if (funnels) {
        $scope.eventFunnels = funnels;
        if (funnels.length > 0) {
          $scope.selectedFunnel = $rootScope.selectedFunnel_name;
          $scope.getFunnelStats($scope.selectedFunnel);
        }
      }
    });
  }
  
  promise = appIceService.hideDisabledFeature();
  promise.then(function(data) {
    if (data[0].features.funnelLaunchbtn) {    
      if ($('#launchcampbtn-funnel').length > 0) $('#launchcampbtn-funnel').hide();
        }

        if(data[0].features.reports){
          if ($('#exportFunnelBtn').length > 0) $('#exportFunnelBtn').hide();
        }

  });

  //On click next step of create Audience
  $scope.nextStep = function() {
    let event = []  
    let selectedEventArr = Array.from(
      document.querySelectorAll("input[type='radio'].campaign:checked")
    );


    //validation for check box
    if(selectedEventArr.length !== $scope.funnelStats.length){
      alert("Please select steps to create campaign");
      return false;
    }

    selectedEventArr.forEach(function(event) {
      let e =  event.value.split('+');
      let operand = e[0];
      let since = e[1];
      let funnel = $scope.funnelStats.filter((ele) => ele.key == operand);
      let users = funnel[0].users;
      prepareAudienceObject(operand,since,users,funnel[0].events);
    
    });
  };

// Prepare Audience Oject for Launch campaign
 function prepareAudienceObject(operand,since,users, events){
    let obj = {
        operand: "",
        operator: "",
        value: "",
        category: "Events",
        attr: "",
        since: {
          have: ""
       }
    };
    obj.operand = operand;
    obj.attr = events.attributeName ? events.attributeName  : '';
    obj.operator = events.operator ? events.operator : '';
    obj.since.have = since;
    obj.value = events.value ? events.value : '';
    $scope.audObj.segmentinfo.what.push(obj);
    document.getElementById("funnel_steps").style.display = 'none';
    document.getElementById("aud_detail").style.display = 'block';
    document.getElementById("next").style.display = 'none';
    document.getElementById("save_aud").style.display = 'inline-block';

 }

 //Create Audience from selected Funnel Graph
 $scope.createAud = function(){
   let range = 0;
   let audience_name = $("#aud_name").val();
   let audience_description = $("#aud_description").val();
   if(audience_name == "" || audience_description =="")
    {
      alert("Please Enter audience name and description");
      return false;
    }
    else{
      appIceService.createAudienceSegment($scope.objectId.$$state.value,range,audience_name,audience_description,$scope.audObj.segmentinfo)
      .then(res=>{
        if(res) {
        window.location.href = appiceEncode.encodePayload(window.location.origin+"/dashboard?action=camp#/camp/create");
      }
    })
    .catch(err=>{
       
    })

      
    }
 }
//Resets audience object creation
 $scope.cancelStep = function(){
    $("input[type='radio']:checked").prop("checked", false);
   $scope.audObj = {
     segmentinfo: {
      who: [],
      what: [],
      where: [],
      when: []
    }
  }
  document.getElementById("aud_detail").style.display = 'none';
  document.getElementById("funnel_steps").style.display = 'block';
  document.getElementById("save_aud").style.display = 'none';
  document.getElementById("next").style.display = 'inline-block';

 }
  $scope.getFunnelStatsBy = function() {
    if ($scope.funnel != "") {
      $scope.getFunnelStats($scope.funnel);
    }
  };

  function objectId () {
    return appIceService.getObjectId()
	}
	function hex (value) {
		return Math.floor(value).toString(16)
	}


  //Get Funnel Chart Data from funnel stats
  $scope.getFunnelStats = function(funnel) {
    $scope.funnelName = funnel.name;
    $("#overlay").show();
    $("#page-loader").show();
    $scope.platform = $("#fddlPlatform").val();
    $scope.funnel = funnel;
    var offSet = semusiCommon.addOffset(
      parseInt(moment.utc().valueOf() / 1000)
    );
    promise = appIceService.getEventFunnelStats(
      funnel,
      $scope.actorProperty,
      $scope.platform,
      offSet
    );
    promise
      .then(function(funnelStatsData) {
        $("#page-loader").hide();
        $("#funnel_loader").hide();
        $("#overlay").hide();
        $scope.funnelStats = [];
        $scope.max = 1;
        $scope.tranMax = 1;
        if (funnelStatsData.length > 0) {
          
          funnelStatsData.forEach(ele => {
         
            var obj = {
              users: ele.count,
              key: ele.name,
              timeStamp : ele.timeStamp,
              lastTimeStamp : ele.lastTimeStamp,
              customUnit : ele.customUnit,
              events : ele.events,
              p : ele.p,
              attribute: (ele?.events?.attributes) ? ele.events.attributes : "" 
            };
            if (obj.key.match(/_\d+$/)) {
              obj.key = obj.key.replace(/_\d+$/, ''); 
            }
            if (obj.events.eventName && obj.events.eventName.match(/_\d+$/)) {
              obj.events.eventName = obj.events.eventName.replace(/_\d+$/, '');
            }
            $scope.funnelStats.push(obj);
          });

          //Calculate % through and % dropouts. It requires minimum of two events
          var len = $scope.funnelStats.length;

          if (len > 0) {
            var labels = [];
            var values = [];
            $scope.funnelStats.forEach(stats => {
              values.push(stats.users);
              labels.push({
                display: `${stats.key} ${stats.attribute ? `- (${stats.attribute.map(attr => attr.attributeName).join(', ')})` : ''}`,                
                key: stats.key,
                attribute: stats.attribute // Add attribute to the label here
              });
            });

            let formattedLabels = labels.map(label => label.display);

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

            graph = new FunnelGraph({
              container: ".funnel",
              gradientDirection: "horizontal",
              data: {
                labels: formattedLabels,
                colors: ["orange", "red"],
                values: values
              },
              direction: "horizontal",
              height: 300,
              width: 600,
              displayPercent: true
            });

            graph.draw();

            let percent = $(".label__percentage").val();
            if (percent == "NaN%") {
              $(".label__percentage").val("0%");
            }
          }
        }
      })
      .catch(function(error) {
        $("#overlay").hide();
        $("#page-loader").hide();
      });
  };

  $("#fddlPlatform").val("All");
  $("#fplatform").text("All");

  // select platform
  $(".fplatform-select").on("click", function() {
    var data = $(this).attr("data-attr");
    if (data == "all") {
      $("#fplatform").text("All");
    } else if (data == "android") {
      $("#fplatform").text("Android");
    } else if (data == "ios") {
      $("#fplatform").text("iOS");
    }
    $("#fddlPlatform").val(data);

    // check funnel
    if ($scope.funnel != "") {
      $scope.getFunnelStats($scope.funnel);
    }
  });

  $("#funnelsState").bootstrapSwitch("state", false);
  $(".bootstrap-switch-label").css("background", "#f5f5f5");
  $("#funnelsState").on("switchChange.bootstrapSwitch", function(event, state) {
    if (state) {
      var text = "Users";
      $("#funnelsState").bootstrapSwitch("labelText", text);
      $(".showTransaction").show();
      $(".showUsers").hide();
    } else {
      var text = "Transaction";
      $("#funnelsState").bootstrapSwitch("labelText", text);
      $(".showUsers").show();
      $(".showTransaction").hide();
    }
  });

  /**
   * selectedColumn method fills the selected step attributes in scope array  
  */
 
  $scope.selectedColumn = function(){ 
     $scope.selectedAttribute = $scope.funnelStats;
 
     let selectedEventArr = Array.from(
      document.querySelectorAll("input[type='checkbox'].exports:checked")
     );
 
     var arr = new Array();
     selectedEventArr.forEach(function(event) {
       let e =  event.value.split('+');
       let operand = e[0];
       arr.push({"operand":operand});
     });
     // Filter objects from array1 that have matching id in array2
     $scope.filteredSelectedAttribute = $scope.selectedAttribute.filter(obj1 =>
     arr.some(obj2 => obj2.operand === obj1.events.eventName));
   }

  $scope.selectedArributes = function(){
    $scope.filteredAttributes = [];
    $scope.attrArray = [];
    let selectedAttributesArray = Array.from(
      document.querySelectorAll("input[type='checkbox'].attr:checked")
    );

    let selectedAttributesDate = Array.from(
      document.querySelectorAll("input[type='checkbox'].dateCol:checked")
    );

    selectedAttributesDate.forEach((item) => {
      $scope.attrArray.push({name : item.name, value : item.value, index: item.dataset.index });
    })
   
    selectedAttributesArray.forEach((item) => {
      $scope.attrArray.push({name : item.name, value : item.value, index: item.dataset.index});
    })
    if(selectedAttributesArray.length > 0){
    $scope.filteredAttributes = [$scope.attrArray.reduce(function(accObj, currentObj) {
      accObj[currentObj.name] = accObj[currentObj.name] || [];
      accObj[currentObj.name].push(currentObj);
      return accObj;
    }, {})]; //{} is the accumulator object
   }
  }

  $scope.exportCheck = function(){
    var count;
    let length = document.querySelectorAll(".statsHaveDone").length
    document.querySelectorAll(".statsHaveDone").forEach((e) => {
    e.addEventListener("change", function(){
      count = this.name;
      if(e.checked){
        for(let i = 0; i < count ; i++ ){
          document.querySelectorAll(".statsHaveDone")[i].checked = 'true';
        }
      }else{
        for(let i = 0; i < length ; i++ ){
          document.querySelectorAll(".statsHaveDone")[i].checked = e.checked;
          document.querySelectorAll(".statsHaveNotDone")[i].checked = e.checked;
        }
      }
      document.querySelectorAll(".statsHaveNotDone")[count].checked = false;
      
    })
  })

  document.querySelectorAll(".statsHaveNotDone").forEach((e) => {
    e.addEventListener("change", function(){
      count = this.name;
      for(let i = 0; i < count ; i++ ){
        document.querySelectorAll(".statsHaveDone")[i].checked = 'true';
      }
      document.querySelectorAll(".statsHaveDone")[count].checked = false;
    })
  })
  
  }

  $scope.selectAllColumns = function(){
    let length = document.querySelectorAll('.allSelectColumn').length
    if($scope.selectAll){ 
     for(let i = 0; i < length; i++){
       document.querySelectorAll('.allSelectColumn')[i].checked = 'true'
     }
     
    }else{
     for(let i = 0; i < length; i++){
       document.querySelectorAll('.allSelectColumn')[i].checked = false
     }
    }
 }

 $scope.AttributeCheck = function(){
  let length = document.querySelectorAll('.allSelectColumn').length
  let checkedLength = document.querySelectorAll("input[type='checkbox'].allSelectColumn:checked").length;
  if(length === checkedLength){
    document.getElementById('selectAll').checked = 'true'
  }
  document.querySelectorAll(".allSelectColumn").forEach((e) => {
    e.addEventListener("change", function(){
      if(!e.checked){
        document.getElementById('selectAll').checked = false
      }
    })
  })
}

  $scope.selectSortedAttr = function(attr){
    if(attr){
    $("#SortBy_").show();
    if(attr.name == 'column'){
      $scope.sortedAttribute = {...attr, col : 'column' }
    } else {
    let selectedEventArr = Array.from(
      document.querySelectorAll("input[type='checkbox'].exports:checked")
    );
    if(selectedEventArr.length > 1) {
      var arr = new Array();
      selectedEventArr.forEach(function(event) {
      let e =  event.value.split('+');
       let operand = e[0];
       arr.push(operand);
      })

      $scope.sortedAttribute = { ...attr, step : `step${arr.indexOf(attr.name) + 1}Segment -> '${attr.value}'` }
    }else{
      $scope.sortedAttribute = attr;
    }
   }
   }else{
    $("#SortBy_").hide();
   }
  }

  $scope.selectedSortValue = function(value){
    if(value){
      $scope.sortBy = value;
    }
  }
  
 
   /* funnel download code start from here */
  $scope.downloadFunnel = async function() {
    let selectedEventArr = Array.from(
      document.querySelectorAll("input[type='checkbox'].exports:checked")
    );

    var arry = new Array();
    selectedEventArr.forEach(function(event) {
      let e =  event.value.split('+');
      let operand = e[0];
      let since =  (e[1] === 'h') ? 1 :0;
      arry.push({"operand":operand,"status":since,"category":"Events","since":{"have":e[1]}});
    });

    function extractAttributeColumns() {
      var attrColumns = [];
      if ($scope.filteredAttributes && $scope.filteredAttributes.length > 0) {
        // Track already processed operands for the current context
        const processedOperands = new Set();

        $scope.filteredAttributes.forEach((item) => {
          arry.forEach((selectedEvent) => {
            if (Object.keys(item).includes(selectedEvent.operand) && !processedOperands.has(selectedEvent.operand)) {
              // Find all positions of the selectedEvent.operand
              const positions = arry
                .map((e, index) => e.operand === selectedEvent.operand ? index : -1)
                .filter(index => index !== -1);

              positions.forEach((pos) => {
                attrColumns.push(
                  {
                    "col": `${`step${pos + 1}key`}`,
                    "alias": `${selectedEvent.operand}`,
                    "type": 'event'
                  },
                  {
                    "col": `${`step${pos + 1}date`}`,
                    "alias": `${selectedEvent.operand}_Date`
                  }
                );

                item[selectedEvent.operand].forEach((attr) => {
                  if (parseInt(attr.index) === pos) {
                    attrColumns.push(
                      {
                        "col": `'${attr.value}'`,
                        "alias": `${selectedEvent.operand}_${attr.value.split(" ").join("")}`,
                        "type": "attribute",
                        "event": selectedEvent.operand,
                        "index": attr.index
                      },
                      {
                        "col": `${`step${pos + 1}Segment->> '${attr.value}'`}`,
                        "alias": `${selectedEvent.operand}_${attr.value.split(" ").join("")}Value`,
                        "type": "value",
                        "index": attr.index
                      }
                    );
                  }
                });
              });

              // Mark the operand as processed
              processedOperands.add(selectedEvent.operand);
            }
          });
        });
      }
      else {
        // Track already processed operands
        const processedOperands = new Set();

        arry.forEach((selectedEvent) => {
          // Check if the operand has already been processed
          if (!processedOperands.has(selectedEvent.operand)) {
            // Find all positions of the selectedEvent.operand
            const positions = arry
              .map((e, index) => e.operand === selectedEvent.operand ? index : -1)
              .filter(index => index !== -1);

            positions.forEach((pos) => {
              attrColumns.push(
                {
                  "col": `${`step${pos + 1}key`}`,
                  "alias": `${selectedEvent.operand}`,
                  "type": 'event'
                },
                {
                  "col": `${`step${pos + 1}date`}`,
                  "alias": `${selectedEvent.operand}_Date`
                }
              );
            });

            // Mark the operand as processed
            processedOperands.add(selectedEvent.operand);
          }
        });

      }
      return attrColumns;
    }
    
    var selector = Object();
    selector.generate = true;
    selector.countOrData = false;
    selector.execute = false;
    selector.sortBy = $scope.sortBy;
    selector.timeStamp = ($scope.funnelStats.length) > 0 ? $scope.funnelStats[0].timeStamp : undefined;
    selector.lastTimeStamp = ($scope.funnelStats.length) > 0 ? $scope.funnelStats[0].lastTimeStamp : undefined;
    selector.customUnit = ($scope.funnelStats.length) > 0 ? $scope.funnelStats[0].customUnit : undefined;
    selector.events =  ($scope.funnelStats.length) > 0 ? $scope.funnelStats : undefined;
    selector.p = ($scope.funnelStats.length) > 0 ? $scope.funnelStats[0].p : undefined;
    selector.export = true;   // flag for export/reachcount
    selector.column = {}
    selector.column.userProperties = [{
          "col": "a.did",
          "alias": "deviceId"
        },{
          "col": "a.user_info->>'e'",
          "alias": "email"
        },{
          "col": "a.user_info->>'p'",
          "alias": "phone"
        },{
        "col": "a._custom_userid",
        "alias": "userid"
      }];
    
    var attrColumns = extractAttributeColumns();
    selector.column.attributeColumns = [...attrColumns]; 
    selector.column.sortedAttribute = $scope.sortedAttribute;

    var promise = appIceService.getAudienceReach(JSON.stringify(arry),selector);
		await promise.then(function(counter) {
			$('#overlay').hide();
			$scope.range = 0;
			if(counter){
        let q = JSON.stringify({"q":counter.q});
        var promise = appIceService.startExports(q);
        promise.then(function(result) {
              $("#downModal").hide();

              $("#messageboxsucess").text("Funnel Export Initiated ")
              $("#messagesucess").show();
  
              setTimeout(() => {
                $("#messagesucess").hide();
              },3000)   
              
        });
			}
           	
		})
		.catch(function(){
			$('#overlay').hide();
		});
  };

});
