// Formulaire saisie des notes

$().ready(function () {
  $("#formnotes .note").bind("blur", valid_note);

  $("#formnotes input").bind("paste", paste_text);
  $(".btn_masquer_DEM").bind("click", masquer_DEM);
});

function is_valid_note(v) {
  if (!v) return true;

  var note_min = parseFloat($("#eval_note_min").text());
  var note_max = parseFloat($("#eval_note_max").text());

  if (!v.match("^-?[0-9]*.?[0-9]*$")) {
    return v == "ABS" || v == "EXC" || v == "SUPR" || v == "ATT" || v == "DEM";
  } else {
    var x = parseFloat(v);
    return x >= note_min && x <= note_max;
  }
}

function valid_note(e) {
  var v = this.value.trim().toUpperCase().replace(",", ".");
  if (is_valid_note(v)) {
    if (v && v != $(this).attr("data-last-saved-value")) {
      this.className = "note_valid_new";
      const etudid = parseInt($(this).attr("data-etudid"));
      save_note(this, v, etudid);
    }
  } else {
    /* Saisie invalide */
    this.className = "note_invalid";
    sco_message("valeur invalide ou hors barème");
  }
}

async function save_note(elem, v, etudid) {
  let evaluation_id = $("#formnotes_evaluation_id").attr("value");
  let formsemestre_id = $("#formnotes_formsemestre_id").attr("value");
  $("#sco_msg").html("en cours...").show();
  try {
    const response = await fetch(
      SCO_URL + "/../api/evaluation/" + evaluation_id + "/notes/set",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          notes: [[etudid, v]],
          comment: document.getElementById("formnotes_comment").value,
        }),
      }
    );
    if (!response.ok) {
      sco_message("Erreur: valeur non enregistrée");
    } else {
      const data = await response.json();
      $("#sco_msg").hide();
      if (data.etudids_changed.length > 0) {
        sco_message("enregistré");
        elem.className = "note_saved";
        // Il y avait une decision de jury ?
        if (data.etudids_with_decision.includes(etudid)) {
          if (v != $(elem).attr("data-orig-value")) {
            $("#jurylink_" + etudid).html(
              '<a href="formsemestre_validation_etud_form?formsemestre_id=' +
                formsemestre_id +
                "&etudid=" +
                etudid +
                '">mettre à jour décision de jury</a>'
            );
          } else {
            $("#jurylink_" + etudid).html("");
          }
        }
        // Mise à jour menu historique
        if (data.history_menu[etudid]) {
          $("#hist_" + etudid).html(data.history_menu[etudid]);
        }
        $(elem).attr("data-last-saved-value", v);
      }
    }
  } catch (error) {
    console.error("Fetch error:", error);
    sco_message("Erreur réseau: valeur non enregistrée");
  }
}

function change_history(e) {
  let opt = e.selectedOptions[0];
  let val = $(opt).attr("data-note");
  const etudid = parseInt($(e).attr("data-etudid"));
  // le input associé a ce menu:
  let input_elem = e.parentElement.parentElement.parentElement.childNodes[0];
  input_elem.value = val;
  save_note(input_elem, val, etudid);
}

// Contribution S.L.: copier/coller des notes

function paste_text(e) {
  var event = e.originalEvent;
  event.stopPropagation();
  event.preventDefault();
  var clipb = e.originalEvent.clipboardData;
  var data = clipb.getData("Text");
  var list = data.split(/\r\n|\r|\n|\t| /g);
  var currentInput = event.currentTarget;
  var masquerDEM = document
    .querySelector("body")
    .classList.contains("masquer_DEM");

  for (var i = 0; i < list.length; i++) {
    currentInput.value = list[i];
    var evt = document.createEvent("HTMLEvents");
    evt.initEvent("blur", false, true);
    currentInput.dispatchEvent(evt);
    var sibbling = currentInput.parentElement.parentElement.nextElementSibling;
    while (
      sibbling &&
      (sibbling.style.display == "none" ||
        (masquerDEM && sibbling.classList.contains("etud_dem")))
    ) {
      sibbling = sibbling.nextElementSibling;
    }
    if (sibbling) {
      currentInput = sibbling.querySelector("input");
      if (!currentInput) {
        return;
      }
    } else {
      return;
    }
  }
}

function masquer_DEM() {
  document.querySelector("body").classList.toggle("masquer_DEM");
}