appice.controller("jobsController", function(
    $scope,
    $rootScope,
    $routeParams,
    appIceService,
    $location
  ) {
    init();
    function init() {
    	// TODO  CURRENTLY DONE FOR YONO TB HANDLED LATER
       $("#p1").hide();
       $("#advance-daterange").hide();
      $scope.currentPage = 1;
      $scope.startFrom = 0;
      $scope.pageSize = 5;
      $scope.errorMsg = "";
      $scope.isPassword = false;    // Default set as false 
      $scope.platform = [];
  
   
        $("#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);
          }
        );  

        $scope.showPopup = function(title, msg, type){
          // show popup box
          swal({
              title: title,
              text: msg,
              type: type,
              buttons: ["Select Patient?", "Speed Case?"],
          },function(){
              window.location = encodeURI("/dashboard?action=insideapp#/jobs/export");            
          }) 
      }
        //in case of download failed Show error
        if($routeParams && $routeParams.id){  
          $scope.showPopup('Download Failed', 'Due to some technical difficulties Downloading CSV is Failed' , 'error')
        }
      refreshFunnelList();
    }
    // for get jobs list from mongo
    function refreshFunnelList(sd=undefined, ed=undefined) {
      const availableSoon = "Will be available soon"
      promise = appIceService.getCsvList();
      promise
        .then(function(retData) {
          // retrieve the csv list from the object
          const jobsData = retData?.list ?? [];
          // get the flag to check if we have to show password on UI
          $scope.isPassword = retData?.panelExport ?? false;
          $("#overlay").hide();
          if (jobsData) {
            $scope.eventFunnels = jobsData;
            //Filter for platform
            
            $('#funnels-table').dataTable({
              "order": [],
              'bAutoWidth': false ,
              "bProcessing": true,
              "dom":' <"search"f><"top"l>rt<"bottom"ip><"clear">', // Allign Search
              bDestroy:true,
              "fnDrawCallback": function( oSettings ) {  
            
                  $(".deleteJobs").click(function(){
                    deleteCSV($(this).val()); 
                  });
                  $(".downloadJob").click(function(){
                    downloadJob($(this).val());
                  });
              },
              "aaData": jobsData,// <-- Data source
              "aoColumns": [
                      { 
                        "mData": "filename"},
                      {  "mData": 'status'},
              ],
              
              "aoColumnDefs": [ 
                {
                  "aTargets": [ 2 ],
                  "mData": "createdOn",
                  "mRender": function ( data, type, full ) {
                      return '<label value="' +data +'">'+semusiCommon.getDateAndTimeFromEpoch(parseInt(full.createdOn)*1000) +'</label>';
                  }
                },
                {
                  "aTargets": [ 3 ],
                  "mData": "processeddate",
                  "mRender": function ( data, type, full ) {
                    if(typeof full.processeddate == 'number'){
                      return '<label value="'+ data +'">'+semusiCommon.getDateAndTimeFromEpoch(parseInt(full.processeddate)*1000) +'</label>';
                    }else{
                      return '<label value="'+ data +'">'+availableSoon +'</label>';
                    }
                  }
                },
                {
                "aTargets": [ 4 ],
                "orderable": false,
                "mData": "st",
                "mRender": function ( data, type, full ) {   
                  if(full.status =='processed' && full.downloaded == true){

                      html = "<button type='button' class='downloadJob btn btn-success editable-submit m-r-5 m-b-5 ' title='Download This Jobs' value='"+full._id +"' ><i class='fa fa-download'></i></button>"             
                      html += "<button type='button' class='btn btn-danger editable-submit m-r-5 m-b-5 deleteJobs' id='"+full._id +"' value='"+full._id +"' title='Remove'><i class='fa fa-minus'></i></button>"
                  }else{
                    html = "<button type='button' class='btn btn-danger editable-submit m-r-5 m-b-5 deleteJobs' id='"+full._id +"' value='"+full._id +"' title='Remove'><i class='fa fa-minus'></i></button>"   
                  }
                      return html;
                  }
                }]
            })
          }
        })
        .catch(function(error) {
          $("#overlay").hide();
        });
    }
    /*For Download The CSV */
    downloadJob = function(id){
      const rString = semusiCommon.generateRandomAlphanumericString(12);
      let args ={
        export_id:id,
        app_id : semusiCommon.ACTIVE_APP_ID,
        num :window.btoa(rString)
      }
     window.location.href = appiceEncode.encodePayload(semusiCommon.API_PARTS.data.r + '/downloadExportcsv?api_key='+ semusiCommon.getActiveUser.api_key+'&uniqueNumber='+ semusiCommon.randomNumber() +'&app_id='+ semusiCommon.ACTIVE_APP_ID+'&args='+JSON.stringify(args));
  // Show Popup only if flag is enabled from Api 
  if($scope.isPassword){
     setTimeout(() => {
          swal({
            title: 'The Password for the Downloaded File will be',
            text: rString,
            icon: 'info',
            confirmButtonText: 'Copy', // Custom text for confirm button
        },function(result){
          /* Copy the text inside the text field */
           navigator.clipboard.writeText(rString);
        }) 
     }, 1000);
    }

  }
    //for delete jobs from mongo
    deleteCSV = function(id) {
      if (confirm("Do you want to delete this CSV?")) {
        var promise = appIceService.deleteCsv(id);
        promise.then(function(data) {
          //Refresh the funnels list
          refreshFunnelList();
          resetControls();
        });
      }
    };



    // select flatform 
    $(".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");
   
  });
  
