appice.controller("funnelsTableController", function(
  $scope,
  $rootScope,
  appIceService,
  $location
) {
  init();
  function init() {
        		// TODO  CURRENTLY DONE FOR YONO TB HANDLED LATER
            $("#p1").show();
            $("#advance-daterange").show();
  
    $scope.currentPage = 1;
    $scope.startFrom = 0;
    $scope.pageSize = 5;
    $scope.errorMsg = "";
    $scope.platform = [];


    var promise = appIceService.getEventList();
    promise
      .then(function(events) {
        $("#overlay").hide();
        if (events) {
          $scope.eventList = events.data;
          $scope.eventList = _.sortBy($scope.eventList, "event");
        }
      })
      .catch(function(error) {
        $("#overlay").hide();
      });

   
      $("#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: "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) {
          let sd = moment.utc(start);
          let ed = moment.utc(end);
  
          sd = parseInt(sd.valueOf());
          ed = parseInt(ed.valueOf());
  
          semusiCommon.setDateRange(start, end);
          $("#advance-daterange span").html(
            start.format(semusiCommon.getDateFormatt()) + " - " + end.format(semusiCommon.getDateFormatt())
          );
  
          $(".ms-drop")
            .find("ul")
            .remove();
  
            refreshFunnelList(sd, ed);
        }
      );


    // $("#platformOpt").multiselect({
    //   columns: 1,
    //   includeSelectAllOption: true,
    //   nonSelectedText: "Platform"
    // });

    refreshFunnelList();
  
  
  }

  $scope.create = function(){
    $location.url("/funnels/create");
  }

  function refreshFunnelList(sd=undefined, ed=undefined,platform=undefined) {
    promise = appIceService.getEventFunnels();
    promise
      .then(function(funnels) {
        $("#overlay").hide();
        if (funnels) {
          $scope.eventFunnels = funnels;

          //filter for Dates
          if(sd && ed && sd!=undefined && ed!=undefined){
            funnels = funnels.filter(funnel => {
              funnel.createdOn = funnel.createdOn * 1000;
              if (funnel.createdOn >= sd && funnel.createdOn <= ed) {
                return funnel;
              }
            });
          }

          //Filter for platform
          if(platform && platform!=undefined){
            if(platform == 'all'){ platform = 'All'}
            if(platform == 'android'){ platform = "Android"; }
            if(platform == 'ios'){ platform = "iOS"; }
        
            funnels =  funnels.filter(funnel => {
                      if(funnel.platform == undefined) {funnel.platform = ['Android']}
                      if(platform != "All"){
                        return funnel.platform.includes(String(platform));
                      }else{
                        return funnel;
                      }   
                });    
            }

          $('#funnels-table').dataTable({
            "order": [],
            'bAutoWidth': false ,
            "bProcessing": true,
            "dom":' <"search"f><"top"l>rt<"bottom"ip><"clear">', // Allign Search
            bDestroy:true,
            "aaData": funnels,// <-- Data source
            "fnDrawCallback": function( oSettings ) {
              $(".gotoFunnelsView").click(function(){
                gotoFunnelsView($(this).val())
              });
              $(".copyFunnel").click(function(){
                copyFunnel($(this).val())
              });
              $(".gotoCreateFunnel").click(function(){
                gotoCreateFunnel($(this).val())
              });
              $(".deleteFunnel").click(function(){
                deleteFunnel($(this).val())
              })
            },
            "aoColumns": [
                    { "mData": 'name'},
                    { "mData": 'description',
                      "defaultContent":""
                    },
            ],

            "aoColumnDefs": [ {
              "aTargets": [ 2 ],
              "orderable": false,
              "mData": "st",
              "mRender": function ( data, type, full ) {                
                    return "<button type='button' class='gotoFunnelsView btn btn-success editable-submit m-r-5 m-b-5' value='"+full._id +"' id='"+full._id +"' title='View'><i class='fa fa-eye'></i>"
                      +
                     "<button id='"+full._id +"' value='"+full._id +"' type='button'style='background: #49b6d6; border-color: #49b6d6 !important' class='copyFunnel copybtn btn btn-primary editable-submit m-r-5 m-b-5' title='Copy'><i class='fa fa-copy'></i>"
                      +
                    "<button id='"+full._id +"' value='"+full._id +"' type='button'class='gotoCreateFunnel btn btn-primary  editable-submit m-r-5 m-b-5' title='Edit'><i class='fa fa-edit'></i>"
                      +                            
                    "<button type='button' class='deleteFunnel btn btn-danger editable-submit m-r-5 m-b-5' title='Remove' id='"+full._id +"' value='"+full._id +"' ><i class='fa fa-minus'></i>"

                }
              }]
          })
        }
      })
      .catch(function(error) {
        $("#overlay").hide();
      });
  }



resetControls = function(){
  $scope.platform = [];
}



gotoCreateFunnel = async function(id) {
  var events = await appIceService.getEventList();
  $scope.events = events.data;
    let promise = getFunnelById(id)
    promise.then(funnel=>{
      appIceService.setFunnel(funnel);
      $location.url("/funnels/create");
    })
    .catch(error=>{
       
    })
  }

  deleteFunnel = function(id) {
    if (confirm("Do you want to delete this funnel?")) {
      var promise = appIceService.deleteFunnel(id);
      promise.then(function(data) {
        //Refresh the funnels list
        refreshFunnelList();
        resetControls();
      });
    }
  };

  copyFunnel = function(id) {
    if (confirm("Are you sure want to copy this funnel")) {
      let promise = appIceService.copyFunnel(id);
      promise
        .then(res => {
          refreshFunnelList();
        })
        .catch(err => {
           
        });
    }
  };

  $(".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);
    refreshFunnelList(undefined,undefined,data);
  });
  $("#platform").text("All");


  getFunnelById = function(id){
    let promise = appIceService.getFunnelById(id);
    return promise;
   }

   gotoFunnelsView = function(id){
     let promise = getFunnelById(id);
     promise.then(funnel=>{
      $rootScope.selectedFunnel_name = funnel;
      $location.url("/funnels/view");
     })
     .catch(error=>{
       
     })

   }
  

});
