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

// TODO: error handler for ajax call

window.WPCACONSENTLOG = (function ($) {
  "use strict";
  var logger = {
    // declare public params
    done: false,
  };

  var _ajaxActionLog = "wpca-log-consent",
    _ajaxActionDelete = "wpca-consent-log-delete-by-user",
    _cssClassBtnDeleteConsent = "wpca-btn-delete-consent",
    _timeoutDelete = 2000;

  var events = {
    unbind: function () {
      $(window).off(WPCAFR.getEventName("consent_after"), handlerLogConsent);
      $(window).off(WPCAFR.getEventName("decline_after"), handlerLogDecline);
      $(window).off(
        WPCAFR.getEventName("init_states_before"),
        handlerInitStatesBefore
      );
      $(window).off(WPCAFR.getEventName("reset_after"), handlerResetAfter);
      $("body").off(
        "click",
        "." + _cssClassBtnDeleteConsent,
        handlerClickDeleteLog
      );

      return this;
    },
    bind: function (unbind) {
      if (unbind) {
        this.unbind();
      }

      $(window).on(WPCAFR.getEventName("consent_after"), handlerLogConsent);
      $(window).on(WPCAFR.getEventName("decline_after"), handlerLogDecline);
      $(window).on(
        WPCAFR.getEventName("init_states_before"),
        handlerInitStatesBefore
      );
      $(window).on(WPCAFR.getEventName("reset_after"), handlerResetAfter);
      $("body").on(
        "click",
        "." + _cssClassBtnDeleteConsent,
        handlerClickDeleteLog
      );

      return this;
    },
  };

  /**
   * Success handler for the log
   *
   * @param {Object} r
   */
  function logSuccess(r) {
    try {
      switch (r.state) {
        case "0":
          if (r.errors && r.errors.length) {
            WPIE.log(r.errors);
          }
          break;
        case "1":
          WPIE.log("your consent has been logged successfully.");
          break;
      }
    } catch (exc) {
      WPIE.log(exc.message, exc);
    }
  }

  /**
   * Perform the ajax log
   *
   * @param {string} type
   * @param {Object} args
   */
  function doLog(type, args) {
    try {
      var payload = {},
        data = {};

      data["context"] = wpcaData.ajaxContextConsentLog;
      data["type"] = type;
      data["consent"] = "consent" === type ? "1" : "0";
      data["categories"] = args.categories || [];

      payload["action"] = "wpie-action";
      payload[wpcaData.ns + "_action"] = _ajaxActionLog;
      payload["data"] = data;
      payload["nonce"] = wpcaData.nonce;

      $.post(wpcaData.ajaxurl, payload, logSuccess, "json");
    } catch (exc) {
      WPIE.log(exc.message, exc);
    }
  }

  /**
   * Success handler for the log deletion
   *
   * @param {Object} r
   */
  function deleteSuccess(r, btn) {
    try {
      switch (r.state) {
        case "0":
          if (r.errors && r.errors.length) {
            WPIE.log(r.errors);
          }
          break;
        case "1":
          if (r.out.deleted > 0) {
            btn.html(`Consent log deleted!`);
            WPIE.log(
              `your consent log has been deleted successfully. Deleted entries: ${r.out.deleted}`
            );

            setTimeout(function () {
              WPCAFR.triggerResetConsent();
            }, _timeoutDelete);
          } else {
            btn.processingBntState("default");
            WPIE.log(`no consent logs found for your current ip address.`);
          }
          break;
      }
    } catch (exc) {
      WPIE.log(exc.message, exc);
    }
  }

  /**
   * Determine if having accept buttons
   *
   * @returns {boolean}
   */
  function hasBtnDeleteConsent() {
    return $("." + _cssClassBtnDeleteConsent).length > 0;
  }

  /**
   * Handler for wpca.consent:after event
   *
   * @param {Object} e
   * @param {Object} args
   *
   * @returns {boolean|void}
   */
  function handlerLogConsent(e, args) {
    var type = "consent";
    doLog(type, args);
  }

  /**
   * Handler for wpca.decline:after event
   *
   * @param {Object} e
   * @param {Object} args
   *
   * @returns {boolean|void}
   */
  function handlerLogDecline(e, args) {
    var type = "decline";
    doLog(type, args);
  }

  /**
   * Handler for wpca.initstates:before event
   *
   * @param {Object} e
   * @param {Object} args
   *
   * @returns {boolean|void}
   */
  function handlerInitStatesBefore(e, args) {
    // accept buttons
    if (hasBtnDeleteConsent()) {
      $("." + _cssClassBtnDeleteConsent).hideButton(0);
    } else {
      $("." + _cssClassBtnDeleteConsent).hideButton(1);
    }
  }

  /**
   * Click handler for the delete my consent button
   *
   * @param {Object} e
   */
  function handlerClickDeleteLog(e) {
    try {
      var payload = {},
        data = {},
        btn = $(this);

      data["context"] = wpcaData.ajaxContextConsentLog;

      payload["action"] = "wpie-action";
      payload[wpcaData.ns + "_action"] = _ajaxActionDelete;
      payload["data"] = data;
      payload["nonce"] = wpcaData.nonce;

      $.post(
        wpcaData.ajaxurl,
        payload,
        function (r) {
          deleteSuccess(r, btn);
        },
        "json"
      );
    } catch (exc) {
      WPIE.log(exc.message, exc);
    }
  }

  /**
   * Click event callback for wpca.reset:after event
   *
   * unbind and bind events
   *
   * @param {Object} e
   */
  function handlerResetAfter(e, args) {
    // true === unbind first
    events.bind(true);
  }

  /**
   * Init the automate logic when the DOM is ready
   */
  logger.init = function () {
    try {
      if (this.done) {
        return;
      }

      var requiredGlobals = ["ajaxContextConsentLog", "needLogging"];

      if (null == wpcaData) {
        throw new Error("Missing global param: wpcaData");
      }

      for (var i = 0; i < requiredGlobals.length; i++) {
        if (null == wpcaData[requiredGlobals[i]]) {
          throw new Error("Missing global param: " + requiredGlobals[i]);
        }
      }

      // bind events
      if (wpcaData.needLogging) {
        events.bind();
      }

      this.done = true;
    } catch (exc) {
      WPIE.log(exc.message, exc);
    }
  };

  return logger;
})(jQuery || {}, window.WPCACONSENTLOG || {});

jQuery(function ($) {
  // call init method when DOM is ready and when WPCAFR is ready
  $(window).on(WPCAFR.getEventName("init_ready"), function () {
    WPCACONSENTLOG.init();
  });
});
