export class ViewerEventsController {
  constructor(viewer) {
    this.viewer = viewer;
    this._bound_process_event = this.process_event.bind(this);
    this._bound_listener_map_by_event_controller_type = new Map();
  }
  updateEvents(events_controller) {
    const canvas = this.canvas();
    if (!canvas) {
      return;
    }
    const controller_type = events_controller.type();
    let map = this._bound_listener_map_by_event_controller_type.get(controller_type);
    if (!map) {
      map = new Map();
      this._bound_listener_map_by_event_controller_type.set(controller_type, map);
    }
    map.forEach((listener2, event_type) => {
      canvas.removeEventListener(event_type, listener2);
    });
    map.clear();
    const listener = (event) => {
      this.process_event(event, events_controller);
    };
    for (let event_type of events_controller.activeEventTypes()) {
      canvas.addEventListener(event_type, listener);
      map.set(event_type, listener);
    }
  }
  cameraNode() {
    return this.viewer.camerasController.cameraNode();
  }
  canvas() {
    return this.viewer.canvas();
  }
  init() {
    if (!this.canvas) {
      return;
    }
    this.viewer.scene().eventsDispatcher.traverseControllers((controller) => {
      this.updateEvents(controller);
    });
  }
  registeredEventTypes() {
    const list = [];
    this._bound_listener_map_by_event_controller_type.forEach((map) => {
      map.forEach((listener, event_type) => {
        list.push(event_type);
      });
    });
    return list;
  }
  dispose() {
    const canvas = this.canvas();
    this._bound_listener_map_by_event_controller_type.forEach((map) => {
      if (canvas) {
        map.forEach((listener, event_type) => {
          canvas.removeEventListener(event_type, listener);
        });
      }
    });
  }
  process_event(event, controller) {
    const canvas = this.canvas();
    if (!canvas) {
      return;
    }
    const event_context = {
      viewer: this.viewer,
      event,
      cameraNode: this.cameraNode()
    };
    controller.processEvent(event_context);
  }
}
