import { EVENT_NAMES } from '../../constants/define';

const { PAUSE, RESUME } = EVENT_NAMES.CLIENT_RECORDER;

export default class HeadlessController {
  constructor({ recorder, tracker, loader, overlay, hightlight, contextMenu, store }) {
    this.tracker = tracker;
    this.recorder = recorder;
    this.loader = loader;
    this.overlay = overlay;
    this.store = store;
    this.hightlight = hightlight;
    this.contextmenu = contextMenu;
  }

  getEventLog() {
    return this.recorder._getEventLog();
  }

  init() {
    if (this?.loader) {
      this.loader.init();
    }

    if (this?.overlay) {
      this?.overlay?.mount();
    }

    if (this?.hightlight) {
      this.hightlight.init();
    }

    this._resume();

    window.addEventListener('message', this._handleMessage);
    window.addEventListener('beforeunload', this._pause, true);
    window.addEventListener('load', this._resume, true);
  }

  _handleMessage = (event) => {
    if (event.data && event.data.control) {
      switch (event.data.control) {
        case PAUSE:
          this._pause();
          break;
        case RESUME:
          this._resume();
          break;
        default:
          break;
      }
    }
  };

  _resume = () => {
    try {
      this?._pause();
      const { isPaused, isReplay } = this.store.getState();

      if (!isPaused || isReplay) {
        if (this?.tracker) {
          this.tracker.startTracking();
        }
        if (this?.recorder) {
          this.recorder.init();
        }
        if (this?.contextmenu) {
          this.contextmenu.init();
        }
      }
    } catch (error) {
      console.log('error when resume in HeadlessController: ', error?.message);
    }
  };

  _pause = () => {
    try {
      if (this?.recorder) {
        this.recorder._removeAllListeners();
      }
      if (this?.tracker) {
        this?.tracker?.stopTracking();
      }
      if (this?.contextmenu) {
        this?.contextmenu?.destroy();
      }
    } catch (error) {
      console.log('error when pause in HeadlessController: ', error?.message);
    }
  };
}
