import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import { EXPERIENCE_FAILURE_REASON } from './consts';
/**
 * Check for the completion of an experience based on DOM mutations
 *
 * Uses a MutationObserver to monitor DOM changes and invokes the provided
 * callback when relevant mutations are detected.
 *
 * Will result in success or failure based on the outcome of the callback.
 */
export var ExperienceCheckDomMutation = /*#__PURE__*/function () {
  function ExperienceCheckDomMutation(_ref) {
    var onDomMutation = _ref.onDomMutation,
      observeConfig = _ref.observeConfig;
    _classCallCheck(this, ExperienceCheckDomMutation);
    this.onDomMutation = onDomMutation;
    this.observeConfig = observeConfig;
  }
  return _createClass(ExperienceCheckDomMutation, [{
    key: "start",
    value: function start(callback) {
      var _this = this;
      this.stop();
      var config = this.observeConfig();
      if (!(config !== null && config !== void 0 && config.target)) {
        callback({
          status: 'failure',
          reason: EXPERIENCE_FAILURE_REASON.DOM_MUTATION_TARGET_NOT_FOUND
        });
        return;
      }
      this.mutationObserver = new MutationObserver(function (mutations) {
        try {
          var result = _this.onDomMutation({
            mutations: mutations
          });
          if (result) {
            callback(result);
          }
        } catch (_unused) {
          callback({
            status: 'failure',
            reason: EXPERIENCE_FAILURE_REASON.DOM_MUTATION_CHECK_ERROR
          });
        }
      });
      var target = config.target,
        options = config.options;
      this.mutationObserver.observe(target, options);
    }
  }, {
    key: "stop",
    value: function stop() {
      if (this.mutationObserver) {
        this.mutationObserver.disconnect();
        this.mutationObserver = undefined;
      }
    }
  }]);
}();