let labels = [];
let dataValues = [];
//fungsi tombol clear data
function clearImage() {
    document.getElementById("upload_image").value = "";
    $("#result").empty();
    $("#penjelasan").hide();
    $("#penjelasan").empty();
    $("#hasilDeteksi").hide();
    $("#pie").hide();
    // clearChartData();

  // Tambahkan pemanggilan AJAX untuk menghapus gambar
  $.ajax({
    url: "/delete_image",
    type: "POST",
    success: function (response) {
      console.log(response);
    },
    error: function (error) {
      console.error(error);
    },
  });
}

function getLink(prediction) {
  if (prediction === "GIANT") {
    return "/giant";
  } else if (prediction === "LEUKOSIT") {
    return "/leukosit";
  } else if (prediction === "NORMAL") {
    return "/normal";
  }
}


//Cropping 
$(document).ready(function () {
  var $modal = $("#modal");
  var image = document.getElementById("sample_image");
  var cropper;

  $("#upload_image").change(function (event) {
    var files = event.target.files;

    var done = function (url) {
      image.src = url;
      $modal.modal("show");
    };

    if (files && files.length > 0) {
      reader = new FileReader();
      reader.onload = function (event) {
        done(reader.result);
      };
      reader.readAsDataURL(files[0]);
    }
  });

  //halaman modal image crop
  $modal
    .on("shown.bs.modal", function () {
      cropper = new Cropper(image, {
        aspectRatio: 1,
        viewMode: 3,
        preview: ".preview",
        minCropBoxWidth: 100, // Menetapkan lebar minimum crop box menjadi 100 piksel
        minCropBoxHeight: 100, // Menetapkan tinggi minimum crop box menjadi 100 piksel
        maxCropBoxWidth: 100, // Menetapkan lebar maksimum crop box menjadi 100 piksel
        maxCropBoxHeight: 100, // Menetapkan tinggi maksimum crop box menjadi 100 piksel
      });
    })
    .on("hidden.bs.modal", function () {
      cropper.destroy();
      cropper = null;
    });

  $("#crop").click(function () {
    canvas = cropper.getCroppedCanvas({
      width: 224,
      height: 224,
    });

    canvas.toBlob(function (blob) {
      var reader = new FileReader();
      reader.onloadend = function () {
        var base64data = reader.result.split(",")[1];

        while (base64data.length % 4 !== 0) {
          base64data += "=";
        }
        
//hasil deteksi
        $.ajax({
          url: "/submit",
          method: "POST",
          data: { image: base64data },
          success: function (data) {
            $modal.modal("hide");
            $("#uploaded_image").attr("src", data.img_path);

            var label = data.label;
            var highest_probability = data.highest_probability;

            $("#hasilDeteksi").show();
            $("#result").empty();

                $("#result").append(`
                <div style="display: grid; grid-template-columns: 50% auto; align-items: center;">
                <img id="image" height="80%" width="50%" src="${data.img_path}">
                <div>
                    <h6>Result: ${label}</h6>
                    <p>Greatest Probability: ${highest_probability.toFixed(2)}%</p>
                </div>
            </div>
            <!-- Div untuk konten tambahan -->
            <div>
                <p>The system identifies that the selected object belongs to the class ${label}. For a full explanation, you can click the following button</p>
                 
                <button class="btn btn-sm  bg-gradient-dark  btn-round mb-0 me-1" onclick="location.href='${getLink(label)}'">Read More</button>
            </div>

            `);
            
            
        
                       

        // mengambil data untuk pie chart probabilitas dari respons JSON
        const labels = [data.label];
        
        const dataValues = [data.highest_probability];
        

        for (const label in data.other_probabilities) {
            labels.push(label);
            dataValues.push(data.other_probabilities[label]);
        }

        console.log('Labels:', labels);
        console.log('Data Values:', dataValues);

          // Menentukan warna berdasarkan label
          const backgroundColors = labels.map(label => {
            switch (label) {
                case 'GIANT':
                    return 'rgba(255, 0, 0, 0.7)'; // Merah
                case 'LEUKOSIT':
                    return 'rgba(0, 0, 128, 0.7)'; // Biru tua
                case 'NORMAL':
                    return 'rgba(255, 192, 203, 0.7)'; // pink
                // Tambahkan warna untuk label lain jika diperlukan
                default:
                    return 'rgba(255, 99, 132, 0.7)'; // Warna default
            }
        });

          // Sebagai konfigurasi untuk tampilan pie chart dari warna yang sudah ditentukan
          const config = {
            type: 'pie',
            data: {
                labels: labels,
                datasets: [{
                    data: dataValues,
                    backgroundColor: backgroundColors,
                }]
            },
            options: {
                responsive: true,
                aspectRatio: 1,
                maintainAspectRatio: false,
                width: 100,
                height: 100
            }
          };

        
          // mendapatkan elemen canvas untuk pie chart
          const ctx = document.getElementById('pieChart').getContext('2d');

          // Membuat pie chart menggunakan Chart.js
          if (window.pieChart && window.pieChart.destroy) {
            window.pieChart.destroy();
        }
        
          window.pieChart = new Chart(ctx, config);

          // Menampilkan elemen card setelah chart dibuat
          $("#pie").show();
                
        // Menampilkan kembali elemen card setelah chart dibuat
        const pieCard = document.getElementById('pie');
        pieCard.style.display = 'block';
        
        

          },
          error: function (error) {
            console.log(error);
          },
        });
      };
      reader.readAsDataURL(blob);
    });
  });
});


function clearChartData() {
  labels.length = 0;
  dataValues.length = 0;
}

//modal tutorial 
$(document).ready(function(){
  $('#tutorialCarousel').carousel();
});

function showTutorial() {
  $('#tutorialModal').modal('show'); // Fungsi untuk menampilkan modal
}

    // Fungsi untuk menutup modal
    function closeModal() {
      $('#tutorialModal').modal('hide');
  }

  // menutup modal crop
function closeCrop() {
document.getElementById("upload_image").value = "";
  $('#modal').modal('hide');
}


window.onload = function() {
   showTutorial();
   document.getElementById("upload_image").value = ""; 
};