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

import { default as VectorSource, VectorSourceEvent } from 'ol/source/Vector';
import VectorEventType from 'ol/source/VectorEventType';
import RBush from 'ol/structs/RBush';
import { getUid } from 'ol/util';

// hacky fix for issue in openlayers / rbush to avoid bricking the application with a TypeError
// can be triggered by double-clicking on a polygon vertice while editing, but not releasing the second click
// see https://github.com/openlayers/openlayers/issues/6310
// e.g. when dbl-clicking on vertices while in modification mode and not releasing the second click but dragging
const RBushUpdateOrig = RBush.prototype.update;
RBush.prototype.update = function () {
  try {
    // eslint-disable-next-line prefer-rest-params
    RBushUpdateOrig.apply(this, arguments);
  } catch (e) {
    console.warn('RBush.update failed, to be ignored.', e);
  }
};

// hacky fir for an issue that occurs infrequently when drawing features while also having a selection interaction active
// the .forEach in removeFeatureInternal fails as the array entry does not exist
const VectorSourceRemoveFeatureInternalOrig = VectorSource.prototype.removeFeature;
VectorSource.prototype.removeFeature = function (feature) {
  try {
    // eslint-disable-next-line prefer-rest-params
    VectorSourceRemoveFeatureInternalOrig.apply(this, arguments);
  } catch (e) {
    console.warn('VectorSource.removeFeatureInternal failed, cleaning up.', e);
    const featureKey = getUid(feature).toString();
    const id = feature.getId();
    if (id !== undefined) {
      delete this.idIndex_[id.toString()];
    } else {
      delete this.undefIdIndex_[featureKey];
    }
    this.dispatchEvent(new VectorSourceEvent(VectorEventType.REMOVEFEATURE, feature));
  }
};
