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 class ExperienceCheckDomMutation {
  constructor({
    onDomMutation,
    observeConfig
  }) {
    this.onDomMutation = onDomMutation;
    this.observeConfig = observeConfig;
  }
  start(callback) {
    this.stop();
    const configResult = this.observeConfig();
    const configs = Array.isArray(configResult) ? configResult : [configResult];
    const validConfigs = configs.filter(config => !!(config !== null && config !== void 0 && config.target));
    if (validConfigs.length === 0) {
      callback({
        status: 'failure',
        reason: EXPERIENCE_FAILURE_REASON.DOM_MUTATION_TARGET_NOT_FOUND
      });
      return;
    }
    this.mutationObserver = new MutationObserver(mutations => {
      try {
        const result = this.onDomMutation({
          mutations
        });
        if (result) {
          callback(result);
        }
      } catch {
        callback({
          status: 'failure',
          reason: EXPERIENCE_FAILURE_REASON.DOM_MUTATION_CHECK_ERROR
        });
      }
    });
    for (const config of validConfigs) {
      const {
        target,
        options
      } = config;
      if (target) {
        this.mutationObserver.observe(target, options !== null && options !== void 0 ? options : {
          childList: true
        });
      }
    }
  }
  stop() {
    if (this.mutationObserver) {
      this.mutationObserver.disconnect();
      this.mutationObserver = undefined;
    }
  }
}