import $ from "jquery"
/**
 * Class FaqTab
 */
export default class FaqLikes {
  /**
   * Run when the document is ready.
   *
   * @return {void}
   */

  constructor() {
    this.cache()
  }

  cache() {
    this.faqLikeContainer = $(".post-like-container")
  }

  docReady() {
    if (this.faqLikeContainer.length === 0) return ""

    this.countFaqLikes()
  }

  countFaqLikes() {
    $(document).on("click", ".post-like-container a", function (e) {
      e.preventDefault()
      var $icon_container = $(this)

      var $thumb_icon_class = $icon_container.find("i")

      if ($thumb_icon_class.hasClass("liked")) {
        return false
      }

      $thumb_icon_class.addClass("liked")

      var $loading_msg = $icon_container.data("loading_msg")

      $icon_container.siblings(".count").text($loading_msg)

      // Retrieve post ID from data attribute
      var $post_id = $icon_container.data("post_id")

      $.ajax({
        url: BafFrontendData.ajaxurl,
        type: "POST",
        dataType: "JSON",
        data: {
          action: "bwl_advanced_faq_apply_rating", // action will be the function name
          post_like: true,
          post_id: $post_id,
          _baf_vote_nonce: $icon_container.find("#_baf_vote_nonce").val(),
        },
        success: function (data) {
          // If vote successful
          if (data.status == 0) {
            $icon_container.addClass("voted")
            $icon_container.siblings(".count").text("").append(data.msg)
          }
          if (data.status == 1) {
            $icon_container.addClass("voted")
            $icon_container.siblings(".count").text("").append(data.msg)
          }
        },
        error: function (xhr, textStatus, e) {
          console.log("There was an error saving the update.")
          return
        },
      })

      return false
    })
  }
}
