$(document).ready(function(){
    //make sure change to your own machine ip or dmain url


var url_string = window.location.href;
var url = new URL(url_string);
var searchKey = url.searchParams.get("id");

urlDrop="/dist/js/select2.min.js";
var urltable ="/js/dataTable.js"
var urlrender="/js/renderTable.js"
var urlBase = "http://0.0.0.0:30000";
// var urlBase = "http://10.0.2.2:30000";
var queryEmployeeUrl = urlBase+"/queryAllEmployee";
var queryAllTasksForAProject = urlBase+"/queryAllTasksForAProject";


 
   $("#add-task").on('shown.bs.modal', function () {
    $("#taskWage").keypress(function (e) {
      console.log("pressed")
      //if the letter is not digit then display error and don't type anything
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
       //display error message
       $("#taskWageError").html("Digits Only").show().fadeOut("slow");
          return false;
     }
    });

    $("#estematedTaskDuration").keypress(function (e) {
      console.log("pressed")
      //if the letter is not digit then display error and don't type anything
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
       //display error message
       $("#estematedTaskDurationError").html("Digits Only").show().fadeOut("slow");
          return false;
     }
    });

    $.ajax({
      type: 'GET',
      url: queryEmployeeUrl,
    
      success: function(data, status, jqXHR){
    
        $.getScript( urlDrop, function() {
    
    
          let r = $.map(data, function (obj) {
            obj.id = obj.Record.employeeId; 
            obj.text = obj.Record.firstName+ " "+obj.Record.lastName; 
            return obj;
          });
    
          $("#taskEmployeeID").select2({
            placeholder: 'Select a Employee...',
            theme: "dark",
            data: r,
            
          })
           });
    
    
      },
      error: function(xhr, textStatus, error){
          console.log(xhr.statusText);
          console.log(textStatus);
          console.log(error);
          alert("Error: "+ xhr.responseText);
      }
    });
    
    
    $("#addNewTask").click(function(){
     
      console.log("in modal")
      var addNewTaskUrl = urlBase+"/addNewTask";
      var formData = {
        projectID: searchKey,
        taskName: $('#taskName').val(),
        taskdescreption: $('#taskdescreption').val(),
        taskStatus:$('#taskStatus').val(),
        taskEmployeeID: $('#taskEmployeeID').val(),
        defecaltDegree: $('#defecaltDegree').val(),
        taskWage: $('#taskWage').val(),
        estematedTaskDuration: $('#estematedTaskDuration').val(),
        taskDeadline: $('#taskDeadline').val(),
      }
      // console.log("formData==========================================  ");
      // console.log(formData);

     
      $.ajax({
        type: 'POST',
        url: addNewTaskUrl,
        data: formData,
        success: function(data, status, jqXHR){
          if(status==='success'){
            
           console.log("successfully add user  in blockchain");
            alert("successfully add task  in blockchain");
            //window.location.replace("/projectDetail?id"+searchKey+'"');
         }
        },
        error: function(xhr, textStatus, error){
         console.log("error add project  in blockchain");
    
            console.log(xhr.statusText);
            console.log(textStatus);
            console.log(error);
            alert("Error while adding task: "+ xhr.responseText);
        }
      });
    })
});


$("#modal-edit").on('shown.bs.modal', function () {
  console.log($("#taskhelper").val())

  $("#taskWageEdit").keypress(function (e) {
    console.log("pressed")
    //if the letter is not digit then display error and don't type anything
  if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
     //display error message
     $("#taskWageEditError").html("Digits Only").show().fadeOut("slow");
        return false;
   }
  });

  $("#estematedTaskDurationEdit").keypress(function (e) {
    console.log("pressed")
    //if the letter is not digit then display error and don't type anything
  if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
     //display error message
     $("#estematedTaskDurationEditError").html("Digits Only").show().fadeOut("slow");
        return false;
   }
  });


  $.ajax({
    type: 'GET',
    url: queryEmployeeUrl,
  
    success: function(data, status, jqXHR){
  
      $.getScript( urlDrop, function() {
  
  
        let r = $.map(data, function (obj) {
          obj.id = obj.Record.employeeId; 
          obj.text = obj.Record.firstName+ " "+obj.Record.lastName; 
          return obj;
        });
  
        $("#taskEmployeeID").select2({
          placeholder: 'Select a Employee...',
          theme: "dark",
          data: r,
          
        })
         });
  
  
    },
    
    error: function(xhr, textStatus, error){
        console.log(xhr.statusText);
        console.log(textStatus);
        console.log(error);
        alert("Error: "+ xhr.responseText);
    }
  });


  $.ajax({
    type: 'GET',
    url: querytask,
    data: { key: searchKey },
    crossDomain:true,
    
    success: function(data, status, jqXHR){
        let record = data.Record;
        //console.log(data);
      $("#projectID").text(data.projectID);
        $("#projectName").text(data.projectName);
        $("#descreption").text(data.descreption);
        $("#projectStatus").text(data.projectStatus);


        
       // $("#projectLeaderID").text(data.projectLeaderID);
        //$("#clientID").text(data.clientID);
        
        $("#estimatedBudget").text(data.estimatedBudget);
        $("#estimatedDuration").text(data.estimatedDuration);
        $("#deadline").text(data.deadline);
        $("#createDateTime").text(data.createDateTime);

        ajaxCall2(data.clientID);
        ajaxCall3(data.projectLeaderID);
    },
    error: function(xhr, textStatus, error){
        console.log(xhr.statusText);
        console.log(textStatus);
        console.log(error);
        alert("Error: llllllllllllllllllllll"+ xhr.responseText);
    }
  });


  });

//////////////////////////////////////////////////////////////////////task table
var notStarted=0;
var onHold=0;
var canceled=0;
var success=0;
var inProgress=0;


$.ajax({
    type: 'GET',
    url: queryAllTasksForAProject,
    data: { key: searchKey },
    success: function(data, status, jqXHR){
        let record = data.Record;

        





      
        $.getScript( urlrender, function() {
            $.getScript( urltable, function() {
                   //     console.log("before  data table===== "+data); 
             $('#queryAllTasksTable').DataTable({
                 data: data,
    
                 columns: [                        
                     { 
                         data: 'Record.taskId',
                         render: function (data, type, row, meta) {
                             return ('<tr>' +'<th scope="col">'+'</th>');    
                         },
                     },
         
                     { 
                         data: 'Record.taskName',
                         render: function (data, type, row, meta) {
                             return   ('  <td >' +data + ' </td>')
                         },
                     },
         
                     { 
                         data: 'Record.estematedTaskDuration' ,
                         render: function (data, type, row, meta) {
                             return  '<tr>'+'<th scope="col">'+ '</th>'+'  <td >'+data +' </td>'
                         },
                     },
                     { 
                      data: 'Record.taskDeadline' ,
                      render: function (data, type, row, meta) {
                          return  '<tr>'+'<th scope="col">'+ '</th>'+'  <td >'+data +' </td>'
                      },
                  },
                     { 
                         data: 'Record.defecaltDegree' ,
                         render: function (data, type, row, meta) {
                             return  (
                               '<tr>'+'<th scope="col">'+ '</th>'+'  <td >'+data +' </td>')
                         },
                     },
                     { 
                      data: 'Record.taskWage' ,
                      render: function (data, type, row, meta) {
                          return  '<tr>'+'<th scope="col">'+ '</th>'+'  <td >'+data +' </td>'
                      },
                  },
         
                     { 
                         data: 'Record.taskStatus' ,
                         render: function (data, type, row, meta) {                         
                             return  ('  <td class="project-state">'  + ' <span class="badge ">'+data+'</span>' + ' </td>')
                         },
                     },
         
                     { 
                         data: 'Record' ,
                         render: function (data, type, row, meta) {

                          return (
                            
                           
                                '<button type="button" class="btn btn-secondary" data-toggle="modal" data-target="#modal-edit" id="'+data.taskId+'">'+
                               ' Edit'+
                              '</button>'+
                              ' <script>'+
                              ' $("#'+data.taskId+'").click(function(){'+
                              //'editTask(data)'+
                              '$("#taskhelper").val("'+data+'"); '+
                              '});'+
                              ' </script>'
                            )
                            //  return ('<td  class="project-actions text-right">' +
                            //  '<a  class="btn btn-primary btn-sm" id=viewTask value='+data+'" >' +
                            //  '  <i class="fas fa-folder">' +
                            //  '  </i>'+
                            //  '   View' +
                            //  ' </a>' +
                            //  '<a class="btn btn-info btn-sm" href="#" >'+
                            //  '<i class="fas fa-pencil-alt">' +
                            //  ' </i>' +
                            //  ' Edit'+
                            //  ' </a>'  +
                            //  ' </td>'+ 
                            //  '</tr>' 
                            //  );
                         
                         },


                     },
                 ],
    
             });
            //  $('#queryAllTasksTable tbody').on('click', 'button', function () {
            //   var data = table.row($(this).parents('tr')).data();
            //   alert(data[1] + data[2]);
    
    
            //  });




             });
         });


console.log(data)
for (let i = 0; i < data.length; i++) {
 // console.log("i="+i)
  //console.log(data[i].Record.taskStatus)

          switch(data[i].Record.taskStatus) {
            case "Not Started":
              // console.log("in")
               notStarted++;
              // console.log(notStarted)
              break;
            case "On Hold":
              onHold++;
              break;
            case "In progress":
              inProgress;
              break;
            case "Canceled":
              canceled++;
              break;  
            case "Success":
              success++;
              break 

         }
   
         
       
      }
var donutChartCanvas = $('#donutChart').get(0).getContext('2d')
var donutData        = {
  labels: [
    'Canceled',
      'Success',
      'In progress',
      'Not Started',
      'On Hold',
      
  ],
  datasets: [
    {
      //data: [7,4,5,4,4],
     data: [canceled,success,inProgress,notStarted,onHold],
      backgroundColor : ['#f56954', '#00a65a', '#f39c12', '#00c0ef' ,'#d2d6de'],
    }
  ]
}

var donutOptions     = {
  maintainAspectRatio : false,
  responsive : true,
}
//Create pie or douhnut chart
// You can switch between pie and douhnut using the method below.
new Chart(donutChartCanvas, {
  type: 'doughnut',
  data: donutData,
  options: donutOptions
})
    },
    error: function(xhr, textStatus, error){
        console.log(xhr.statusText);
        console.log(textStatus);
        console.log(error);
        alert("Error: llllllllllllllllllllll"+ xhr.responseText);
    }
  });

////////////////////////////////////////////////////////////





 
});
$(document).ajaxStart(function(){
  $("#wait").css("display", "block");
});
$(document).ajaxComplete(function(){
  $("#wait").css("display", "none");
});

function editTask(data)
{
      console.log(data)          
  // setTimeout(function(){ alert("After 5 seconds!"); }, 5000);
  //       $("#taskIDEdit").text(data.taskId);   
  //       $("#taskNameEdit").val(data.taskName);  
  //       $("#taskdescreptionEdit").val(data.taskdescreption);  
  //       $("#taskStatusEdit").val(data.taskStatus);  
  //       $("#taskEmployeeEdit").val(data.taskEmployeeID).trigger('change');
  //       $("#defecaltDegreeEdit").val(data.defecaltDegree);  
  //       $("#taskWageEdit").val(data.taskWage);  
  //       $("#estematedTaskDurationEdit").val(data.estematedTaskDuration);  
  //       $("#taskDeadlineEdit").val(data.taskDeadline);  


}