'use strict';
define(() => {
  let mustNotSelfOverlapRule = {

    $get: ($q, $filter, GeometryFactory) => {

      const mustNotSelfOverlap = (editDescription) => {
        const defer = $q.defer();
        const geometry = editDescription && editDescription.editedfeature ? editDescription.editedfeature.getGeometry() : null;

        // mustNotSelfOverlap est une règle réservée aux objets linéaire pour l'instant (KIS-2828)
        if (geometry && (geometry.getType() === 'LineString' || geometry.getType() === 'MultiLineString')) {

          // géométrie au format Geojson
          const format = new ol.format.GeoJSON();
          const geometryAsGeojson = format.writeGeometryObject(geometry);

          GeometryFactory.isLineSelfOverlapping(geometryAsGeojson).then(
              res => {
                if (typeof res.data === 'boolean') {
                  if (res.data) {
                    // isLineSelfOverlapping renvoie true => chevauchement => règle non validée
                    require('toastr').error($filter('translate')('rulecfg.mustNotSelfOverlap.error'));
                    defer.reject('mustNotSelfOverlap');

                  } else {
                    // isLineSelfOverlapping renvoie false => pas de chevauchement => règle validée
                    defer.resolve();
                  }
                } else {
                  // le retour n'est pas de type boolean. Il s'est passé une erreur serveur hors exception interceptée
                  require('toastr').error(
                      $filter('translate')('rulecfg.mustNotSelfOverlap.currentRule')
                      + '\n' + $filter('translate')('rulecfg.mustNotSelfOverlap.serverError')
                  );
                }
              }
          );
        } else {
          // l'objet en cours d'édition ne contient pas de géométrie linéaire
          require('toastr').error(
              $filter('translate')('rulecfg.mustNotSelfOverlap.currentRule')
              + '\n' + $filter('translate')('rulecfg.mustNotSelfOverlap.noLineError')
          );
          defer.reject('mustNotSelfOverlap');
        }
        return defer.promise;
      };
      return {
        mustNotSelfOverlap: mustNotSelfOverlap
      };
    }
  };

  mustNotSelfOverlapRule.$get.$inject = ['$q', '$filter', 'GeometryFactory'];
  return mustNotSelfOverlapRule;
});