appice.controller("journeyTableController", function(
  $scope,
  $rootScope,
  appIceService,
  $location,
  $routeParams
) {
  init();
  $scope.PANEL_URL = window.location.origin;
  $scope.journeyList=[];
  $scope.platform = 'all';
  $scope.sd;
  $scope.ed;
  //Initilize default property/data
  function init() {
    $("#p1").show();
    $("#advance-daterange").show();
    appIceService.removeJourneyView();

    //Initilizing date picker

    $("#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) {
        $scope.sd = moment.utc(start);
        $scope.ed = moment.utc(end);

        $scope.sd = parseInt( $scope.sd.valueOf());
        $scope.ed = parseInt( $scope.ed.valueOf());

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

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

          getJourneyList();
      }
    );
    getJourneyList();
    
  }

  //Get filtered journey list
  function getJourneyList(){
    appIceService.getJourneysList().then(Journeydata => {

      //filter for Dates
      if($scope.sd && $scope.ed && $scope.sd!=undefined && $scope.ed!=undefined){
        Journeydata = Journeydata.filter(journey => {
          journey.createdOn = journey.createdOn * 1000;
          if (journey.createdOn >= $scope.sd && journey.createdOn <= $scope.ed) {
            return journey;
          }
        });
    }

    //filter for platform
    if($scope.platform && $scope.platform!=undefined){
      //Case for previous created journey
      Journeydata.forEach(ele => {
        if(ele.platform === undefined){
          ele.platform = 'all';
        }
      });

      if($scope.platform != 'all'){
      Journeydata = Journeydata.filter(journey => journey.platform && journey.platform === $scope.platform);
      }
    }

    $scope.journeyList = Journeydata;
     
    $('#funnels-table').dataTable({
          "order": [],
          'bAutoWidth': false ,
          "bProcessing": true,
          "dom":' <"search"f><"top"l>rt<"bottom"ip><"clear">', // Allign Search
          bDestroy:true,
          "aaData": Journeydata,// <-- Data source
          "fnDrawCallback": function( oSettings ) {
            $(".gotoJourneyView").click(function(){
              gotoJourneyView($(this).attr("id"))
            });
            $(".copyJourney").click(function(){
              copyJourney($(this).val())
            });
            $(".gotoCreateJourney").click(function(){
              gotoCreateJourney($(this).val())
            });
            $(".deleteJourney").click(function(){
              deleteJourney($(this).attr("id"))
            })
          },
          "aoColumns": [
                  { "mData": 'journeyName'},
                  { "mData": 'journeyDescription',
                    "defaultContent":""
                  },
                  {"mData":'startEvent'},
                  {"mData":'endEvent'}
          ],

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

          }
            }]
        })
  }).catch(err => {
     
  })
  }
 

  //Delete Current Jounrey
  deleteJourney = function(id) {
    if (confirm("Do you want to delete this journey?")) {
      var promise = appIceService.deleteJourney(id);
      promise.then(function(data) {
        //Refresh the Journey list
        $("#messageboxsucess").text("Journey Successfully Deleted")
			$("#messagesucess").show();
			setTimeout(() => {
				$("#messagesucess").hide();
			},3000)
        init();
        resetControls();
      });
    }
  };

	$('.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)
		$scope.platform = data;
		getJourneyList();
	});
	$('#platform').text('All');

  //Go to Create Journey
  gotoCreateJourney = function(id) {
    let promise = getJourneyById(id)
    promise.then(funnel=>{
      appIceService.setJourney(funnel);
      $("#container").html("");
      window.location.replace(window.location.origin+"/dashboard?action=insideapp#/journey/create");
    })
    .catch(error=>{
       
    })
  }
  //Get Jounrey By Id
  getJourneyById = function(id){
    let promise = appIceService.getJourneyById(id);
    return promise;
   }

    //Go to View Journey Chart
   gotoJourneyView = function(id) {
     $routeParams.view = true;
   	let promise = getJourneyById(id)
    promise.then(journey=>{
      appIceService.setJourneyView(journey);
      $location.url("/journey/view");
    })
    .catch(error=>{
       
    })
   }

   //Copy Current Jouney
   copyJourney = function(id){
    if (confirm("Are you sure want to copy this journey")) {
      let promise = appIceService.copyJourney(id);
      promise
        .then(res => {
          init();
        })
        .catch(err => {
           
        });
    }
   } 


});




























