/**
 * Ajax loop with rest api
 *
 * load more loop post by ajax scripts
 * @version 3.0.0
 */

document.querySelectorAll(".js-retheme-loop-load").forEach((loadmore) => {
  loadmore.addEventListener("click", (event) => {
     event.preventDefault();

     const _this = event.currentTarget;
     const target = _this.getAttribute("data-target");
     const targetElement = document.getElementById(target);
     const currentPage = parseInt(_this.getAttribute("data-current-page"));
     const totalPage = parseInt(_this.getAttribute("data-total-page"));
     const postTotal = parseInt(_this.getAttribute("data-post-total"));
     const settings = _this.getAttribute("data-setting");

     // Before load new element
     _this.classList.add("is-loading");
     _this.innerHTML = retheme_query_ajax.text.loading;
     targetElement.classList.add("rt-loading");

     // Ajax load more
     fetch(retheme_query_ajax.apiurl, {
        method: "POST",
        credentials: "same-origin",
        headers: {
           "Content-Type": "application/x-www-form-urlencoded",
        },
        body: new URLSearchParams({
           action: "result",
           page: currentPage + 1,
           query: settings,
        }),
     })
        .then((response) => response.json())
        .then((response) => {
           if (response) {
              // New post insert html
              targetElement.innerHTML += response;

              // Set current page with new paged
              const newPaged = currentPage + 1;

              // Set new current page
              _this.setAttribute("data-current-page", newPaged);

              // // Remove loading animation
              setTimeout(function () {
                 targetElement.classList.remove("rt-loading");
                 _this.classList.remove("is-loading");
                 _this.innerHTML = retheme_query_ajax.text.loadmore;
              }, 500);

              // Remove button loadmore on lastest page
              if (newPaged == totalPage) {
                 _this.parentNode.remove();
              }
           }
        })
        .catch((error) => {
           if (confirm(retheme_query_ajax.text.errorMessage) == true) {
              window.location.reload();
           }
           console.log(error);
        });
  });
});
