const DrawSources = {
  HOT: "mapbox-gl-draw-hot",
  COLD: "mapbox-gl-draw-cold"
};
export default {
  created() {
    this.$_initMapboxDom();
    this.drawEvents = this.$_initMapboxEvent().draw;
  },

  methods: {
    $_initMapboxDom() {
      window.mapboxDom = window.mapboxDom || {};
      window.mapboxDom.draw = window.mapboxDom.draw || {};
      return window.mapboxDom;
    },

    $_initMapboxEvent() {
      window.mapboxEvent = window.mapboxEvent || {};
      window.mapboxEvent.draw = window.mapboxEvent.draw || [];
      return window.mapboxEvent;
    },

    $_addDrawControl(control) {
      if (!control) return;
      this.$_removeDrawControl();
      window.mapboxDom.draw = control;
      this.map && this.map.addControl(control);
    },

    $_removeSource(source) {
      if (this.map.getSource(source)) {
        const { layers } = this.map.getStyle();

        if (layers) {
          layers
            .filter(layer => layer.source === source)
            .forEach(layer => this.map.removeLayer(layer.id));
        }
        this.map.removeSource(source);
      }
    },

    $_removeDrawControl() {
      if (
        window.mapboxDom.draw &&
        window.mapboxDom.draw.onAdd &&
        window.mapboxDom.draw.onRemove
      ) {
        if (!this.map) return;

        this.$_removeSource(DrawSources.HOT);
        this.$_removeSource(DrawSources.COLD);

        this.map.removeControl(window.mapboxDom.draw);
      }
    },

    $_bindDrawEvents(eventName, eventCallback) {
      if (!this.map) return;
      this.drawEvents.push({
        name: eventName,
        callback: eventCallback
      });
      this.map.on(eventName, eventCallback);
    },

    $_unbindDrawEvents() {
      if (!this.map) return;
      if (this.drawEvents.length <= 0) return;
      this.drawEvents.forEach(e => {
        this.map && this.map.off(e.name, e.callback);
      });
      this.drawEvents.length = 0;
    }
  }
};
