/*
 * Copyright (C) 2018 Robert Bosch GmbH Copyright (C) 2018 Robert Bosch Manufacturing Solutions GmbH, Germany. All rights reserved.
 */

import type { EventsKey } from 'ol/events';
import Interaction from 'ol/interaction/Interaction';
import Map from 'ol/Map';
import { unByKey } from 'ol/Observable';

export abstract class InteractionMode {
  protected map: Map;
  private extendedModes: InteractionMode[] = [];
  private activeInteractions: Interaction[] = [];
  private olListeners: EventsKey[] = [];

  private _isActive: boolean;

  get isActive() {
    return this._isActive;
  }

  setMap(map: Map) {
    this.map = map;
    this.extendedModes.forEach((mode) => mode.setMap(map));
  }

  extends(mode: InteractionMode) {
    this.extendedModes.push(mode);
    return this;
  }

  activate() {
    if (this.isActive) {
      return;
    }

    this._isActive = true;
    this.extendedModes.forEach((mode) => mode.activate());
  }

  deactivate() {
    if (!this.isActive) {
      return;
    }

    this.extendedModes.forEach((mode) => mode.deactivate());

    unByKey(this.olListeners);
    this.olListeners.length = 0;

    this.activeInteractions.forEach((interaction) => this.map.removeInteraction(interaction));
    this.activeInteractions.length = 0;
    this._isActive = false;
  }

  protected registerListener(eventKey: EventsKey): void {
    this.olListeners.push(eventKey);
  }

  protected activateInteraction(interaction: Interaction): void {
    this.map.addInteraction(interaction);
    this.activeInteractions.push(interaction);
  }
}
