"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ExperienceCheckDomMutation = void 0;
var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));
var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));
var _consts = require("./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.
 */
var ExperienceCheckDomMutation = exports.ExperienceCheckDomMutation = /*#__PURE__*/function () {
  function ExperienceCheckDomMutation(_ref) {
    var onDomMutation = _ref.onDomMutation,
      observeConfig = _ref.observeConfig;
    (0, _classCallCheck2.default)(this, ExperienceCheckDomMutation);
    this.onDomMutation = onDomMutation;
    this.observeConfig = observeConfig;
  }
  return (0, _createClass2.default)(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: _consts.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: _consts.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;
      }
    }
  }]);
}();