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

import Collection from 'ol/Collection';
import { altKeyOnly } from 'ol/events/condition';
import Feature from 'ol/Feature';
import Modify, { ModifyEvent } from 'ol/interaction/Modify';
import { Observable, Subject } from 'rxjs';
import { InteractionMode } from '../interaction-mode';

export class ModificationInteractionMode extends InteractionMode {
  readonly modify = new Modify({
    features: this.selectedFeatures,
    // only add new vertices if alt is pressed (if you change this, please test for selection issues while adding vertices)
    insertVertexCondition: altKeyOnly,
  });
  private _modification = new Subject<ModifyEvent>();
  readonly modified: Observable<ModifyEvent> = this._modification.asObservable();
  private _modificationStart = new Subject<ModifyEvent>();
  readonly modifying: Observable<ModifyEvent> = this._modificationStart.asObservable();

  constructor(private selectedFeatures?: Collection<Feature>) {
    super();
  }

  activate() {
    // first activate extended interactions so that modification comes last (priority to vertex operations instead of selection)
    super.activate();
    this.activateInteraction(this.modify);
    this.registerListener(this.modify.on('modifystart', (event: ModifyEvent) => this._modificationStart.next(event)));
    this.registerListener(this.modify.on('modifyend', (event: ModifyEvent) => this._modification.next(event)));
  }
}
