import Draw from 'ol/interaction/Draw';
import DoubleClickZoom from 'ol/interaction/DoubleClickZoom';

import VectorSource from "ol/source/Vector";

class DrawTool {
  constructor(map, callback) {
    this.map = map;
    this.source = new VectorSource();

    this.callback = callback;

    this.doubleClickZoom = this.map.getInteractions().getArray().find(
      interaction => {
        return interaction instanceof DoubleClickZoom;
      }
    );

    this.draw; // global so we can remove it later
  }

  start(measureType) {
    let that = this;
    this.draw = new Draw({
      source: this.source,
      type: measureType,
    });
    this.map.addInteraction(this.draw);

    this.draw.on('drawstart', function (evt) {
      that.map.removeInteraction(that.doubleClickZoom);
    });

    this.draw.on('drawend', function (event) {
      let geometry = event.feature.values_.geometry.clone();
      that.callback(geometry)
      setTimeout(function () {
        that.map.addInteraction(that.doubleClickZoom);
        that.stop();
      }, 100)
    });
  }
  stop() {
    let that = this;
    if (this.draw) {
      this.map.removeInteraction(this.draw);
      this.draw = null;
    }
    if (!this.map.getInteractions().getArray().some(function (interaction) {
      return interaction instanceof DoubleClickZoom
    })) {
      this.map.addInteraction(this.doubleClickZoom);
    }
  }
}

export default DrawTool
