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

window.WPCAAUTOMATE = (function ($) {
  "use strict";
  var automate = {
    done: false,
  };

  var _idTableParent = "general-automate-tmpl",
    _idTable = "automate",
    _idBtnRefresh = "wpca-automate-refresh-btn",
    _cssClassCb = "automate-check",
    _count = 0,
    _checkedCount = 0;

  var events = {
    /**
     * Unbind all events
     *
     * @returns events
     */
    unbind: function () {
      // listen to changed on the check all checkbox
      $("table#" + _idTable + " .wpie-check-all").off(
        "change",
        handler3rdPartyCbAllChange
      );
      // listen to changed on the 3rd party entry checkboxes
      $("table#" + _idTable + " ." + _cssClassCb).off(
        "change",
        handler3rdPartyCbChange
      );
      // listen to a click on the refresh button
      $("#" + _idTableParent).off(
        "click",
        "#" + _idBtnRefresh,
        handlerBtnRefresh
      );

      return this;
    },
    /**
     * Bind all events
     *
     * @returns events
     */
    bind: function () {
      // listen to changed on the check all checkbox
      $("table#" + _idTable + " .wpie-check-all").on(
        "change",
        handler3rdPartyCbAllChange
      );
      // listen to changed on the 3rd party entry checkboxes
      $("table#" + _idTable + " ." + _cssClassCb).on(
        "change",
        handler3rdPartyCbChange
      );
      // listen to a click on the refresh button
      $("#" + _idTableParent).on(
        "click",
        "#" + _idBtnRefresh,
        handlerBtnRefresh
      );

      return this;
    },
  };

  /**
   * Handler for click event on Refresh button
   *
   * @param {Object} e
   */
  function handlerBtnRefresh(e) {
    var btn = $(this);

    e.preventDefault();

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

    var args = WPIESETT.getAjaxArgs("wpca-automate-refresh", {});
    $.get(
      ajaxurl,
      args,
      function (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.table) {
                // add the updated table HTML
                $("#" + _idTable).replaceWith(r.out.table);
                if (r.out.added && $.isArray(r.out.added)) {
                  $("#" + _idTable)
                    .find("tr")
                    .removeClass("added");
                  var k, name;
                  // for each new item, add the "added" css class
                  for (k in r.out.added) {
                    name = r.out.added[k];
                    $("#" + _idTable)
                      .find("tr." + name)
                      .addClass("added");
                  }
                  // remove the "added" css class with a delay
                  setTimeout(function () {
                    $("#" + _idTable)
                      .find("tr")
                      .removeClass("added");
                  }, 500);
                }
              }
              break;
          }
          // enable the button after refreshing
          btn.prop("disabled", false).setLoadingImg(false);
        } catch (exc) {
          btn.prop("disabled", false).setLoadingImg(false);
          WPIE.log(exc.message, exc);
        } finally {
          // unbind events and bind again
          events.unbind().bind();
        }
      },
      "json"
    );
  }

  /**
   * Handler for on change event on the check all checkbox
   *
   * @param {Object} e
   */
  function handler3rdPartyCbAllChange(e) {
    var checked = $(this).isChecked();

    if (checked && !WPCA_SETT.elAutoErase.isChecked()) {
      WPCA_SETT.elAutoErase.trigger("click");
    } else if (!checked && WPCA_SETT.elAutoErase.isChecked()) {
      WPCA_SETT.elAutoErase.trigger("click");
    }

    _checkedCount = checked ? _count : 0;
  }

  /**
   * Handler for on change event on all checkboxes in the 3rd party list
   *
   * @param {Object} e
   */
  function handler3rdPartyCbChange(e) {
    var checkbox = $(this),
      checked = checkbox.isChecked(),
      elCheckAll = $("table#" + _idTable + " .wpie-check-all");

    if (checked) {
      _checkedCount++;
    } else {
      _checkedCount--;
    }

    // trigger a click on the "Automatic cookie blocking" checkbox
    if (0 < _checkedCount && !WPCA_SETT.elAutoErase.isChecked()) {
      WPCA_SETT.elAutoErase.trigger("click");
    } else if (0 === _checkedCount && WPCA_SETT.elAutoErase.isChecked()) {
      WPCA_SETT.elAutoErase.trigger("click");
    }

    // check or uncheck the all checkbox
    if (0 < _checkedCount && _checkedCount === _count) {
      elCheckAll.cbCheck();
    } else if (0 === _checkedCount || _checkedCount !== _count) {
      elCheckAll.cbCheck(false);
    }
  }

  /**
   * Init the automate logic when the DOM is ready
   *
   * Tasks:
   * 	- set params
   * 	- callings function events.bind()
   *
   */
  automate.init = function () {
    if (this.done) {
      return;
    }
    if (null == WPCA_SETT || false === WPCA_SETT.done) {
      throw new Error("Could not continue. WPCA_SETT object is not ready.");
    }

    _count = $("table#" + _idTable + " ." + _cssClassCb).length;
    _checkedCount = $(
      "table#" + _idTable + " ." + _cssClassCb + ":checked"
    ).length;

    // check the check all checkbox if needed
    if (0 < _checkedCount && _checkedCount === _count) {
      $("table#" + _idTable + " .wpie-check-all").cbCheck();
    }

    // bind all events
    events.bind();

    this.done = true;
  };

  return automate;
})(jQuery || {}, window.WPCAAUTOMATE || {});

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