<!-- sortable -->
<script src="https://unpkg.com/sortablejs-make/Sortable.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-sortablejs@latest/jquery-sortable.js"></script>

<script type="text/javascript">
  /**
   * tutor-training lessons listing page script.
   * @script start
   */
  
  var learningContentSlug = "<%=tutorTrainingContent.slug%>";
  listingLessons();

  function listingLessons(searchStr = "") {
    $(".course-list").empty();
    $.ajax({
      type: "POST",
      url: "/tutor-training/" + learningContentSlug + "/lessons/listing",
      dataType: "html",
      data: {
        contentSlug: learningContentSlug,
        searchStr: searchStr,
      },
      success: function (response) {
        $(".course-list").html(response);
      },
      complete: function () {
        $(".loader").hide();
      },
    });
  }

  $("#lessonForm").submit(function (e) {
    e.preventDefault();
    $("#lessonCrudBtn").attr("disabled", true);
    $(document).find("span.text-danger").remove();
    var formData = $("#lessonForm").serialize();
    var url = $("#lessonForm").attr("action");
    $.ajax({
      type: "POST",
      url: url,
      dataType: "json",
      data: formData,
      beforeSend: function () {
        $(".loader").show();
      },
      success: function (response) {
        if (response.success == true) {
          location.reload();
        }
      },
      error: function (response) {
        let errorMessages = "";
        $.each(response.responseJSON.errors, function (field_name, error) {
          $(document)
            .find("[id=" + error.param + "]")
            .after(
              '<span class="help-block text-danger">' + error.msg + "</span>"
            );
        });
      },
      complete: function () {
        $(".loader").hide();
        $("#lessonCrudBtn").attr("disabled", false);
      },
    });
  });

  jQuery(document).on("click", ".editLesson", function () {
    let title = $(this).attr("data-title");
    let id = $(this).attr("data-id");
    if (title) {
      $("#title").val(title);
      $("#lessonForm").attr(
        "action",
        "/tutor-training/" + learningContentSlug + "/lessons/update/" + id
      );
      $(".addLesson").html("Update Lesson");
      $("html, body").animate({ scrollTop: 0 }, "slow");
    }
  });

  $("#searchString").keyup(function () {
    let searchStr = $(this).val().trim();
    if(searchStr){
      listingLessons(searchStr);
    }else{
      listingLessons();
    }
  });

  //this function will be executed on click of X (clear button)
  $('input[type=search]').on('search', function () {
    listingLessons();
  });

  $(".sortable").sortable({
    swapThreshold: 1,
    group: "list",
    animation: 200,
    onChange: function (update, evt) {
      var j = 1;
      $(".lesson-grid").each(function () {
        $(this).attr("data-position", j);
        j++;
      });
    },
    onSort: function (evt, ui) {
      var positions = [];
      $(".lesson-grid").each(function () {
        positions.push([
          $(this).attr("data-lesson-id"),
          $(this).attr("data-position"),
        ]);
      });
      $.ajax({
        url:"/tutor-training/" +learningContentSlug +"/lessons/update-position",
        method: "POST",
        data: {
          positions: positions,
        },
        dataType: "json",
        beforeSend: function () {
        },
        success: function (response) {
        },
        error: function (response) {
          Swal.fire({
            title: "Oops...",
            text: response.message,
          });
        },
        complete: function () {
          // circleChart();
        },
      });
    },
  });

  (function ($) {
    $.fn.circleChart = function () {
      this.each(function () {
        var percentage = $(this).data("percentage");
        var inner_text = $(this).text();
        $(this).html(makeSvg(percentage, inner_text));
      });
      return this;
    };
  })(jQuery);

  $(".mark-complete").click(function () {
    $("sort-slides").addClass("sortable-chosen");
  });

  function makeSvg(percentage, inner_text = "") {
    var abs_percentage = Math.abs(percentage).toString();
    var percentage_str = percentage.toString();
    var classes = "";

    if (percentage < 0) {
      classes = "danger-stroke circle-chart__circle--negative";
    } else if (percentage > 0 && percentage <= 30) {
      classes = "warning-stroke";
    } else {
      classes = "success-stroke";
    }

    var svg =
      '<svg class="circle-chart" viewbox="0 0 33.83098862 33.83098862" xmlns="http://www.w3.org/2000/svg">' +
      '<circle class="circle-chart__background" cx="16.9" cy="16.9" r="15.9" />' +
      '<circle class="circle-chart__circle ' +
      classes +
      '"' +
      'stroke-dasharray="' +
      abs_percentage +
      ',100"    cx="16.9" cy="16.9" r="15.9" />' +
      '<g class="circle-chart__info">' +
      '   <text class="circle-chart__percent" x="17.9" y="15.5">' +
      percentage_str +
      "%</text>";

    if (inner_text) {
      svg +=
        '<text class="circle-chart__subline" x="16.91549431" y="22">' +
        inner_text +
        "</text>";
    }

    svg += " </g></svg>";

    return svg;
  }

  
  var inputOptionsPromise = new Promise(function (resolve) {
    setTimeout(function (myObj) {
      let allLearningContents = '<%-JSON.stringify(allLearningContents) %>';
      allLearningContents = JSON.parse(allLearningContents);
       
      myObj = [];
      for (content of allLearningContents) {
        myObj[content._id] = content.title;
      }
      resolve(myObj);
    }, 2000);
  });

  
  $(document).on("change click", ".lesson-duplication", function (event) {
    var lessonId = $(this).attr("data-lesson-id");
    var lessonName = $(this).attr("data-lesson-name");
    var contentSlug = $(this).attr("data-content-slug");
    var learningContentId = "";

    Swal.fire({
      html:
        '<p>Select the learningContent where you want to copy this lesson "<strong>' +
        lessonName +
        '</strong>"</p>',
      input: "select",
      inputOptions: inputOptionsPromise,
      inputPlaceholder: "Select a training content",
      showCancelButton: true,
      confirmButtonText: `Confirm`,
      inputValidator: (value) => {
        return new Promise(function (resolve, reject) {
          if (value !== "") {
            resolve();
          } else {
            resolve("Select a training content");
          }
        });
      },
      willOpen: () => {
          setTimeout(() => {
            var selectElement = $('select');

            selectElement.select2({
              width: '100%',
              placeholder: "Select a training content",
              allowClear: true
            });
            // selectElement.addClass('select-lesson-duplicate');
          }, 100);
        }
    }).then(function (result) {
      if (result.isConfirmed) {
        $.ajax({
          type: "POST",
          url: "/tutor-training/" + contentSlug + "/lessons/duplicate-lesson",
          data: {
            lessonId: lessonId,
            learningContentId: result.value,
          },
          beforeSend: function () {
            $(".loader").show();
          },
          success: function (response) {
            new Noty({
              theme: "relax",
              text: response.message,
              type: "success",
              layout: "topRight",
              timeout: 1500,
            }).show();

            setTimeout(function() {
            window.location.reload(true); // Force reload with cache bypass (optional)
            }, 1000);
          },
          error: function (response) {
            new Noty({
              theme: "relax",
              text: response.responseJSON.message,
              type: "error",
              layout: "topRight",
              timeout: 1500,
            }).show();
          },
          complete: function () {
            $(".loader").hide();
          },
        });
      }
    });
  });
  /**
   * tutor-training lessons listing page script.
   * @script end
   */
</script>
