/*
 * Please see wp-cookie-allow.php for more details.
 *
 * @author $Author: Vincent Weber <weepie-plugins@outlook.com> $
 * @since 3.2.3
 */

window.WPCACONSENTLOGSETT = (function ($) {
  "use strict";
  var settings = {
    // declare public params
    tableParentDiv: {},
    table: {},
    filterTxtField: {},
    filterBtn: {},
  };

  var _idTableParent = "wpca-log-list",
    _idTable = "logs",
    _idTxtFieldFilter = "wpca-consent-log-filter",
    _idBtnFilter = "wpca-consent-log-filter-btn",
    _idBtnDeleteAll = "wpca-consent-log-delete-all-btn",
    _idBtnExport = "wpca-consent-log-export-btn",
    _idExportDownloadLink = "wpca-consent-log-download-link",
    _classRowDelete = "wpie-list-row-field-delete",
    _classIconDelete = "wpca-consent-log-delete",
    _allowedFilterCol = ["ip", "IP"],
    _defaultCol = "ip",
    _maxLengthColNeedles = {
      ip: 39, // ip address can has a max length of 39 chars (ipv6)
    };

  var _ajaxActionFilter = "wpca-consent-log-filter",
    _ajaxActionDelete = "wpca-consent-log-delete",
    _ajaxActionDeleteAll = "wpca-consent-log-delete-all",
    _ajaxActionExportAll = "wpca-consent-log-export";

  /**
   * Determine if given column is allowed for filtering
   *
   * @param {string} col
   *
   * @returns {boolean}
   */
  function isAllowedFilterCol(col) {
    if ("string" !== typeof col) {
      return false;
    }
    return -1 !== _allowedFilterCol.indexOf(col);
  }

  /**
   * Success handler for the filter
   *
   * @param {Object} r
   */
  function fitlerSuccess(r) {
    try {
      switch (r.state) {
        case "0":
          if (r.errors && r.errors.length) {
            WPIE.log(r.errors);
          }
          WPIE.alert(wpcaDatal10n.error_occured);
          break;
        case "1":
          if (0 < r.out.count) {
            // add the updated table HTML
            $("#" + _idTable).replaceWith(r.out.table);
          } else {
            WPIE.alert(wpcaDatal10n.log_filter_no_results);
          }
          break;
      }
    } catch (exc) {
      WPIE.log(exc.message, exc);
    }
  }

  /**
   * Success handler for the delete process
   *
   * @param {Object} r
   */
  function deleteSuccess(r) {
    try {
      switch (r.state) {
        case "0":
          if (r.errors && r.errors.length) {
            WPIE.log(r.errors);
          }
          WPIE.alert(wpcaDatal10n.error_occured);
          break;
        case "1":
          if (0 < r.out.deleted) {
            $("#" + _idTable)
              .find('tr[data-id="' + r.out.deleted + '"]')
              .remove();
          }
          break;
      }
    } catch (exc) {
      WPIE.log(exc.message, exc);
    }
  }

  /**
   * Success handler for the delete all process
   *
   * @param {Object} r
   */
  function deleteAllSuccess(r) {
    try {
      switch (r.state) {
        case "0":
          if (r.errors && r.errors.length) {
            WPIE.log(r.errors);
          }
          WPIE.alert(wpcaDatal10n.error_occured);
          break;
        case "1":
          if (r.out.deleted) {
            // add the updated table HTML
            $("#" + _idTable).replaceWith(r.out.table);
          } else {
            WPIE.alert(wpcaDatal10n.log_filter_no_results);
          }
          break;
      }
    } catch (exc) {
      WPIE.log(exc.message, exc);
    }
  }

  /**
   * Success handler for the export process
   *
   * @param {Object} r
   */
  function exportSuccess(r) {
    try {
      switch (r.state) {
        case "0":
          if (r.errors && r.errors.length) {
            WPIE.log(r.errors);
          }
          WPIE.alert(wpcaDatal10n.error_occured);
          break;
        case "1":
          if (r.out.exported && !!r.out.data) {
            const a = document.createElement("a");
            document.body.appendChild(a);
            a.style = "display: none";

            const blob = new Blob([r.out.data], { type: "octet/stream" }),
              url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = r.out.filename;
            a.click();
            window.URL.revokeObjectURL(url);
          } else {
            WPIE.alert(wpcaDatal10n.log_export_no_results);
          }
          break;
      }
    } catch (exc) {
      WPIE.log(exc.message, exc);
    }
  }

  /**
   * Handler for click event on Refresh button
   *
   * @param {Object} e
   *
   * @returns {void} with invalid data
   */
  function handlerBtnFilter(e) {
    e.preventDefault();
    var thiz = e.data.thiz,
      btn = $(this),
      col = _defaultCol,
      needle;

    // get the filter value
    needle = thiz.filterTxtField.val().trim();
    // basic filter value validation
    if ("" === needle) {
      return;
    }

    // remove white spaces and lower case the needle
    needle = needle.trim().toLowerCase();

    if (-1 !== needle.indexOf("|")) {
      var parts = needle.split("|");
      // the filter column
      col = parts[0];
      // the needle witout the column
      needle = parts[1];

      // return if column is not allowed and show an alert message
      if (!isAllowedFilterCol(col)) {
        WPIE.alert(wpcaDatal10n.log_filter_not_possible.replace("%COL%", col));
        return;
      }
    }

    // return if column needle is exceeds the allowed max and show an alert message
    if (_maxLengthColNeedles[col] < needle.length) {
      WPIE.alert(
        wpcaDatal10n.log_filter_not_possible_value_max
          .replace("%COL%", col)
          .replace("%MAX%", _maxLengthColNeedles[col])
      );
      return;
    }

    // disable the button while refreshing
    btn.prop("disabled", true).setLoadingImg(true);

    // setup ajax arguments
    var args = WPIESETT.getAjaxArgs(_ajaxActionFilter, {
      ndl: needle,
      col: col,
    });

    // do ajax request
    $.get(
      ajaxurl,
      args,
      function (r) {
        fitlerSuccess(r);
      },
      "json"
    )
      // if fails, log the error
      .fail(function (XMLHttpRequest, textStatus, errorThrown) {
        WPIE.log(XMLHttpRequest.statusText);
      })
      // reset filter fields and button
      .always(function () {
        settings.filterTxtField.val("");
        // enable the button after refreshing
        settings.filterBtn.prop("disabled", false).setLoadingImg(false);
      });
  }

  /**
   * Handler for click event on Delete icon
   *
   * @param {Object} e
   */
  function handlerClickDelete(e) {
    var icon = $(this),
      tr = icon.parents("tr"),
      id = tr.data("id");

    if (confirm(wpcaDatal10n.log_filter_del_confirm)) {
      // setup ajax arguments
      var args = WPIESETT.getAjaxArgs(_ajaxActionDelete, { id: id });

      $.post(ajaxurl, args, deleteSuccess, "json")
        // if fails, log the error
        .fail(function (XMLHttpRequest, textStatus, errorThrown) {
          WPIE.log(XMLHttpRequest.statusText);
        })
        // reset filter fields and button
        .always(function () {});
    } else {
      e.preventDefault();
      return false;
    }
  }

  /**
   * Handler for click event on Delete All button
   *
   * @param {Object} e
   */
  function handlerClickDeleteAll(e) {
    if (confirm(wpcaDatal10n.log_filter_del_all_confirm)) {
      var thiz = e.data.thiz,
        btn = $(this);

      // disable the button while refreshing
      btn.prop("disabled", true).setLoadingImg(true);

      // setup ajax arguments
      var args = WPIESETT.getAjaxArgs(_ajaxActionDeleteAll, {});

      // do ajax request
      $.post(ajaxurl, args, deleteAllSuccess, "json")
        // if fails, log the error
        .fail(function (XMLHttpRequest, textStatus, errorThrown) {
          WPIE.log(XMLHttpRequest.statusText);
        })
        // reset filter fields and button
        .always(function () {
          // enable the button after refreshing
          btn.prop("disabled", false).setLoadingImg(false);
        });
    } else {
      e.preventDefault();
      return false;
    }
  }

  /**
   * Handler for click event on the export button
   *
   * @param {Object} e
   */
  function handlerClickExport(e) {
    if (confirm(wpcaDatal10n.log_export_confirm)) {
      var thiz = e.data.thiz,
        btn = $(this);

      // disable the button while refreshing
      btn.prop("disabled", true).setLoadingImg(true);

      // setup ajax arguments
      var args = WPIESETT.getAjaxArgs(_ajaxActionExportAll, {});

      // do ajax request
      $.get(ajaxurl, args, exportSuccess, "json")
        // if fails, log the error
        .fail(function (XMLHttpRequest, textStatus, errorThrown) {
          WPIE.log(XMLHttpRequest.statusText);
        })
        // reset filter fields and button
        .always(function () {
          // enable the button after refreshing
          btn.prop("disabled", false).setLoadingImg(false);
        });
    } else {
      e.preventDefault();
      return false;
    }
  }

  /**
   * Init all events
   *
   * @returns void
   */
  settings.events = function () {
    var thiz = this;

    this.tableParentDiv.on(
      "click",
      "#" + _idBtnFilter,
      { thiz: this },
      handlerBtnFilter
    );
    this.tableParentDiv.on(
      "click",
      "." + _classIconDelete,
      { thiz: this },
      handlerClickDelete
    );
    this.tableParentDiv.on(
      "click",
      "#" + _idBtnDeleteAll,
      { thiz: this },
      handlerClickDeleteAll
    );
    this.tableParentDiv.on(
      "click",
      "#" + _idBtnExport,
      { thiz: this },
      handlerClickExport
    );

    // trigger btn filter when hitting 'Enter' key on input text or add btn
    this.tableParentDiv.on(
      "keypress",
      "#" + _idTxtFieldFilter,
      { thiz: this },
      function (e) {
        if (13 === (e.keyCode || e.which)) {
          $("#" + _idBtnFilter).trigger("click");
        }
      }
    );
  };

  /**
   * Init the automate logic when the DOM is ready
   */
  settings.init = function () {
    try {
      // init DOM elements
      this.tableParentDiv = $("#" + _idTableParent);
      this.table = $("table#" + _idTable);
      this.filterTxtField = $("#" + _idTxtFieldFilter);
      this.filterBtn = $("#" + _idBtnFilter);

      // init all events
      this.events();
    } catch (exc) {
      WPIE.log(exc.message, exc);
    }
  };

  return settings;
})(jQuery || {}, window.WPCACONSENTLOGSETT || {});

jQuery(function ($) {
  // call init method when DOM is ready
  WPCACONSENTLOGSETT.init();
});
