import { r as registerInstance, c as createEvent, h, H as Host, g as getElement } from './index-79805253.js';

/**
 * https://github.com/blakeyc/conversions/blob/master/src/conversions.js
 *
 * */
function convertToMetres(value, unit) {
  switch (unit) {
    case 'km':
      return value * 1000;
    case 'mi':
      return value * (1 / 0.000621371);
    case 'rad': {
      value = value / 0.0174533;
      value = degrees2meters(value, value)[0];
      return value;
    }
    case 'deg':
      return degrees2meters(value, value)[0];
    default:
      return value; // metres
  }
}
function convertToUnit(value, unit) {
  switch (unit) {
    case 'km':
      return value / 1000;
    case 'mi':
      return value * 0.000621371;
    case 'rad':
      return meters2degrees(value, value)[0] * 0.0174533;
    case 'deg':
      return meters2degrees(value, value)[0];
    default:
      return value; // metres
  }
}
function degrees2meters(lon, lat) {
  // credit:  https://gist.github.com/onderaltintas/6649521
  var x = (lon * 20037508.34) / 180;
  var y = Math.log(Math.tan(((90 + lat) * Math.PI) / 360)) / (Math.PI / 180);
  y = (y * 20037508.34) / 180;
  return [x, y];
}
function meters2degrees(x, y) {
  // credit:  https://gist.github.com/onderaltintas/6649521
  var lon = (x * 180) / 20037508.34;
  //thanks magichim @ github for the correction
  var lat = (Math.atan(Math.exp((y * Math.PI) / 20037508.34)) * 360) / (Math.PI - 90);
  return [lon, lat];
}
function round(value, decimals) {
  const roundedNumber = +parseFloat(value).toFixed(decimals);
  return roundedNumber;
}
function ConvertUnit(value, fromUnit, toUnit) {
  const inputValue = +value;
  const from = fromUnit;
  const to = toUnit;
  if (!inputValue)
    throw new Error('Missing value to convert!');
  if (!from || !to)
    throw new Error('Unit/Alias not currently supported!');
  return round(convertToUnit(convertToMetres(inputValue, from), to), 3);
}

const gdSpatialPickerCss = "gd-spatial-picker{box-sizing:content-box;display:inline-block;position:relative}.map-container{width:100%;height:100%;position:relative;min-width:10rem;padding:0.5rem;font-size:1rem;color:#212529;text-align:left;list-style:none;background-color:#fff;background-clip:padding-box;border:1px solid rgba(0, 0, 0, 0.15);border-radius:0.25rem}gd-spatial-picker.spatial-icon-btn{position:relative;display:flex}.spatial-icon-btn .spatial-btn-wrapper{position:relative}.spatial-icon-btn bs-button.spatial-button{border-radius:0px;height:100%;display:flex}.spatial-btn-wrapper .map-container{display:flex;justify-content:center;margin:0px;padding:0px}.spatial-icon-btn .map-wrapper{position:absolute;right:0px;width:inherit;height:inherit;z-index:1;padding:25px;margin:0px;border:1px solid #ececec;background-color:white}.spatial-icon-btn .map-wrapper.hide{display:none}.reset-range{width:250px;display:flex;justify-content:right;align-items:end;margin-bottom:0.5rem}.inline{display:flex;align-items:center;margin-bottom:0.5rem;margin-right:1rem;width:100%}.spatial-form-select{display:block;width:100%;height:calc(1.5em + 0.75rem + 2px);padding:0.375rem 0.75rem;font-size:1rem;font-weight:400;line-height:1.5;color:#495057;background-color:#fff;background-clip:padding-box;border:1px solid #ced4da;border-radius:0.25rem;transition:border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out}.spatial-form-select:focus{color:#495057;background-color:#fff;border-color:hsla(var(--primary-h), var(--primary-s), calc(var(--primary-l) + 25%), var(--primary-a, 1));outline:0;box-shadow:0 0 0 0.2rem hsla(var(--primary-h), var(--primary-s), var(--primary-l), 0.25)}.spatial-form-select.border-danger:focus{border-color:var(--danger);box-shadow:0 0 0 0.2rem hsla(var(--danger-h), var(--danger-s), var(--danger-l), 0.25)}.leaflet-pane,.leaflet-tile,.leaflet-marker-icon,.leaflet-marker-shadow,.leaflet-tile-container,.leaflet-pane>svg,.leaflet-pane>canvas,.leaflet-zoom-box,.leaflet-image-layer,.leaflet-layer{position:absolute;left:0;top:0}.leaflet-container{overflow:hidden}.leaflet-tile,.leaflet-marker-icon,.leaflet-marker-shadow{-webkit-user-select:none;-moz-user-select:none;user-select:none;-webkit-user-drag:none}.leaflet-tile::selection{background:transparent}.leaflet-safari .leaflet-tile{image-rendering:-webkit-optimize-contrast}.leaflet-safari .leaflet-tile-container{width:1600px;height:1600px;-webkit-transform-origin:0 0}.leaflet-marker-icon,.leaflet-marker-shadow{display:block}.leaflet-container .leaflet-overlay-pane svg,.leaflet-container .leaflet-marker-pane img,.leaflet-container .leaflet-shadow-pane img,.leaflet-container .leaflet-tile-pane img,.leaflet-container img.leaflet-image-layer,.leaflet-container .leaflet-tile{max-width:none !important;max-height:none !important}.leaflet-container.leaflet-touch-zoom{-ms-touch-action:pan-x pan-y;touch-action:pan-x pan-y}.leaflet-container.leaflet-touch-drag{-ms-touch-action:pinch-zoom;touch-action:none;touch-action:pinch-zoom}.leaflet-container.leaflet-touch-drag.leaflet-touch-zoom{-ms-touch-action:none;touch-action:none}.leaflet-container{-webkit-tap-highlight-color:transparent}.leaflet-container a{-webkit-tap-highlight-color:rgba(51, 181, 229, 0.4)}.leaflet-tile{filter:inherit;visibility:hidden}.leaflet-tile-loaded{visibility:inherit}.leaflet-zoom-box{width:0;height:0;-moz-box-sizing:border-box;box-sizing:border-box;z-index:800}.leaflet-overlay-pane svg{-moz-user-select:none}.leaflet-pane{z-index:400}.leaflet-tile-pane{z-index:200}.leaflet-overlay-pane{z-index:400}.leaflet-shadow-pane{z-index:500}.leaflet-marker-pane{z-index:600}.leaflet-tooltip-pane{z-index:650}.leaflet-popup-pane{z-index:700}.leaflet-map-pane canvas{z-index:100}.leaflet-map-pane svg{z-index:200}.leaflet-vml-shape{width:1px;height:1px}.lvml{behavior:url(#default#VML);display:inline-block;position:absolute}.leaflet-control{position:relative;z-index:800;pointer-events:visiblePainted;pointer-events:auto}.leaflet-top,.leaflet-bottom{position:absolute;z-index:1000;pointer-events:none}.leaflet-top{top:0}.leaflet-right{right:0}.leaflet-bottom{bottom:0}.leaflet-left{left:0}.leaflet-control{float:left;clear:both}.leaflet-right .leaflet-control{float:right}.leaflet-top .leaflet-control{margin-top:10px}.leaflet-bottom .leaflet-control{margin-bottom:10px}.leaflet-left .leaflet-control{margin-left:10px}.leaflet-right .leaflet-control{margin-right:10px}.leaflet-fade-anim .leaflet-tile{will-change:opacity}.leaflet-fade-anim .leaflet-popup{opacity:0;-webkit-transition:opacity 0.2s linear;-moz-transition:opacity 0.2s linear;transition:opacity 0.2s linear}.leaflet-fade-anim .leaflet-map-pane .leaflet-popup{opacity:1}.leaflet-zoom-animated{-webkit-transform-origin:0 0;-ms-transform-origin:0 0;transform-origin:0 0}.leaflet-zoom-anim .leaflet-zoom-animated{will-change:transform}.leaflet-zoom-anim .leaflet-zoom-animated{-webkit-transition:-webkit-transform 0.25s cubic-bezier(0, 0, 0.25, 1);-moz-transition:-moz-transform 0.25s cubic-bezier(0, 0, 0.25, 1);transition:transform 0.25s cubic-bezier(0, 0, 0.25, 1)}.leaflet-zoom-anim .leaflet-tile,.leaflet-pan-anim .leaflet-tile{-webkit-transition:none;-moz-transition:none;transition:none}.leaflet-zoom-anim .leaflet-zoom-hide{visibility:hidden}.leaflet-interactive{cursor:pointer}.leaflet-grab{cursor:-webkit-grab;cursor:-moz-grab;cursor:grab}.leaflet-crosshair,.leaflet-crosshair .leaflet-interactive{cursor:crosshair}.leaflet-popup-pane,.leaflet-control{cursor:auto}.leaflet-dragging .leaflet-grab,.leaflet-dragging .leaflet-grab .leaflet-interactive,.leaflet-dragging .leaflet-marker-draggable{cursor:move;cursor:-webkit-grabbing;cursor:-moz-grabbing;cursor:grabbing}.leaflet-marker-icon,.leaflet-marker-shadow,.leaflet-image-layer,.leaflet-pane>svg path,.leaflet-tile-container{pointer-events:none}.leaflet-marker-icon.leaflet-interactive,.leaflet-image-layer.leaflet-interactive,.leaflet-pane>svg path.leaflet-interactive,svg.leaflet-image-layer.leaflet-interactive path{pointer-events:visiblePainted;pointer-events:auto}.leaflet-container{background:#ddd;outline:0}.leaflet-container a{color:#0078a8}.leaflet-container a.leaflet-active{outline:2px solid orange}.leaflet-zoom-box{border:2px dotted #38f;background:rgba(255, 255, 255, 0.5)}.leaflet-container{font:12px/1.5 \"Helvetica Neue\", Arial, Helvetica, sans-serif}.leaflet-bar{box-shadow:0 1px 5px rgba(0, 0, 0, 0.65);border-radius:4px}.leaflet-bar a,.leaflet-bar a:hover{background-color:#fff;border-bottom:1px solid #ccc;width:26px;height:26px;line-height:26px;display:block;text-align:center;text-decoration:none;color:black}.leaflet-bar a,.leaflet-control-layers-toggle{background-position:50% 50%;background-repeat:no-repeat;display:block}.leaflet-bar a:hover{background-color:#f4f4f4}.leaflet-bar a:first-child{border-top-left-radius:4px;border-top-right-radius:4px}.leaflet-bar a:last-child{border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-bottom:none}.leaflet-bar a.leaflet-disabled{cursor:default;background-color:#f4f4f4;color:#bbb}.leaflet-touch .leaflet-bar a{width:30px;height:30px;line-height:30px}.leaflet-touch .leaflet-bar a:first-child{border-top-left-radius:2px;border-top-right-radius:2px}.leaflet-touch .leaflet-bar a:last-child{border-bottom-left-radius:2px;border-bottom-right-radius:2px}.leaflet-control-zoom-in,.leaflet-control-zoom-out{font:bold 18px \"Lucida Console\", Monaco, monospace;text-indent:1px}.leaflet-touch .leaflet-control-zoom-in,.leaflet-touch .leaflet-control-zoom-out{font-size:22px}.leaflet-container .leaflet-control-attribution{background:#fff;background:rgba(255, 255, 255, 0.7);margin:0}.leaflet-control-attribution,.leaflet-control-scale-line{padding:0 5px;color:#333}.leaflet-control-attribution a{text-decoration:none}.leaflet-control-attribution a:hover{text-decoration:underline}.leaflet-container .leaflet-control-attribution,.leaflet-container .leaflet-control-scale{font-size:11px}.leaflet-left .leaflet-control-scale{margin-left:5px}.leaflet-bottom .leaflet-control-scale{margin-bottom:5px}.leaflet-control-scale-line{border:2px solid #777;border-top:none;line-height:1.1;padding:2px 5px 1px;font-size:11px;white-space:nowrap;overflow:hidden;-moz-box-sizing:border-box;box-sizing:border-box;background:#fff;background:rgba(255, 255, 255, 0.5)}.leaflet-control-scale-line:not(:first-child){border-top:2px solid #777;border-bottom:none;margin-top:-2px}.leaflet-control-scale-line:not(:first-child):not(:last-child){border-bottom:2px solid #777}.leaflet-touch .leaflet-control-attribution,.leaflet-touch .leaflet-control-layers,.leaflet-touch .leaflet-bar{box-shadow:none}.leaflet-touch .leaflet-control-layers,.leaflet-touch .leaflet-bar{border:2px solid rgba(0, 0, 0, 0.2);background-clip:padding-box}.leaflet-popup{position:absolute;text-align:center;margin-bottom:20px}.leaflet-popup-content-wrapper{padding:1px;text-align:left;border-radius:12px}.leaflet-popup-content{margin:13px 19px;line-height:1.4}.leaflet-popup-content p{margin:18px 0}.leaflet-popup-tip-container{width:40px;height:20px;position:absolute;left:50%;margin-left:-20px;overflow:hidden;pointer-events:none}.leaflet-popup-tip{width:17px;height:17px;padding:1px;margin:-10px auto 0;-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);-ms-transform:rotate(45deg);transform:rotate(45deg)}.leaflet-popup-content-wrapper,.leaflet-popup-tip{background:white;color:#333;box-shadow:0 3px 14px rgba(0, 0, 0, 0.4)}.leaflet-container a.leaflet-popup-close-button{position:absolute;top:0;right:0;padding:4px 4px 0 0;border:none;text-align:center;width:18px;height:14px;font:16px/14px Tahoma, Verdana, sans-serif;color:#c3c3c3;text-decoration:none;font-weight:bold;background:transparent}.leaflet-container a.leaflet-popup-close-button:hover{color:#999}.leaflet-popup-scrolled{overflow:auto;border-bottom:1px solid #ddd;border-top:1px solid #ddd}.leaflet-oldie .leaflet-popup-content-wrapper{-ms-zoom:1}.leaflet-oldie .leaflet-popup-tip{width:24px;margin:0 auto;-ms-filter:\"progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)\";filter:progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)}.leaflet-oldie .leaflet-popup-tip-container{margin-top:-1px}.leaflet-oldie .leaflet-control-zoom,.leaflet-oldie .leaflet-control-layers,.leaflet-oldie .leaflet-popup-content-wrapper,.leaflet-oldie .leaflet-popup-tip{border:1px solid #999}.leaflet-div-icon{background:#fff;border:1px solid #666}.leaflet-tooltip{position:absolute;padding:6px;background-color:#fff;border:1px solid #fff;border-radius:3px;color:#222;white-space:nowrap;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;pointer-events:none;box-shadow:0 1px 3px rgba(0, 0, 0, 0.4)}.leaflet-tooltip.leaflet-clickable{cursor:pointer;pointer-events:auto}.leaflet-tooltip-top:before,.leaflet-tooltip-bottom:before,.leaflet-tooltip-left:before,.leaflet-tooltip-right:before{position:absolute;pointer-events:none;border:6px solid transparent;background:transparent;content:\"\"}.leaflet-tooltip-bottom{margin-top:6px}.leaflet-tooltip-top{margin-top:-6px}.leaflet-tooltip-bottom:before,.leaflet-tooltip-top:before{left:50%;margin-left:-6px}.leaflet-tooltip-top:before{bottom:0;margin-bottom:-12px;border-top-color:#fff}.leaflet-tooltip-bottom:before{top:0;margin-top:-12px;margin-left:-6px;border-bottom-color:#fff}.leaflet-tooltip-left{margin-left:-6px}.leaflet-tooltip-right{margin-left:6px}.leaflet-tooltip-left:before,.leaflet-tooltip-right:before{top:50%;margin-top:-6px}.leaflet-tooltip-left:before{right:0;margin-right:-12px;border-left-color:#fff}.leaflet-tooltip-right:before{left:0;margin-left:-12px;border-right-color:#fff}.leaflet-draw-section{position:relative}.leaflet-draw-toolbar{margin-top:12px}.leaflet-draw-toolbar-top{margin-top:0}.leaflet-draw-toolbar-notop a:first-child{border-top-right-radius:0}.leaflet-draw-toolbar-nobottom a:last-child{border-bottom-right-radius:0}.leaflet-draw-toolbar a{background-image:url(\"data:image/svg+xml;base64, \") !important;background-repeat:none;background-size:300px 30px;background-clip:padding-box}.leaflet-retina .leaflet-draw-toolbar a{background-image:url(\"data:image/svg+xml;base64, \") !important;background-repeat:none}.leaflet-draw a{display:block;text-align:center;text-decoration:none}.leaflet-draw-actions{display:none;list-style:none;margin:0;padding:0;position:absolute;left:26px;top:0;white-space:nowrap}.leaflet-touch .leaflet-draw-actions{left:32px}.leaflet-right .leaflet-draw-actions{right:26px;left:auto}.leaflet-touch .leaflet-right .leaflet-draw-actions{right:32px;left:auto}.leaflet-draw-actions li{display:inline-block}.leaflet-draw-actions li:first-child a{border-left:none}.leaflet-draw-actions li:last-child a{-webkit-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0}.leaflet-right .leaflet-draw-actions li:last-child a{-webkit-border-radius:0;border-radius:0}.leaflet-right .leaflet-draw-actions li:first-child a{-webkit-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px}.leaflet-draw-actions a{background-color:#919187;border-left:1px solid #aaa;color:#fff;font:11px/19px \"Helvetica Neue\", Arial, Helvetica, sans-serif;line-height:28px;text-decoration:none;padding-left:10px;padding-right:10px;height:28px}.leaflet-touch .leaflet-draw-actions a{font-size:12px;line-height:30px;height:30px}.leaflet-draw-actions-bottom{margin-top:0}.leaflet-draw-actions-top{margin-top:1px}.leaflet-draw-actions-top a,.leaflet-draw-actions-bottom a{height:27px;line-height:27px}.leaflet-draw-actions a:hover{background-color:#a0a098}.leaflet-draw-actions-top.leaflet-draw-actions-bottom a{height:26px;line-height:26px}.leaflet-draw-toolbar .leaflet-draw-draw-polyline{background-position:-2px -2px}.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-draw-polyline{background-position:0 -1px}.leaflet-draw-toolbar .leaflet-draw-draw-polygon{background-position:-31px -2px}.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-draw-polygon{background-position:-29px -1px}.leaflet-draw-toolbar .leaflet-draw-draw-rectangle{background-position:-62px -2px}.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-draw-rectangle{background-position:-60px -1px}.leaflet-draw-toolbar .leaflet-draw-draw-circle{background-position:-92px -2px}.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-draw-circle{background-position:-90px -1px}.leaflet-draw-toolbar .leaflet-draw-draw-marker{background-position:-122px -2px}.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-draw-marker{background-position:-120px -1px}.leaflet-draw-toolbar .leaflet-draw-edit-edit{background-position:-152px -2px}.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-edit-edit{background-position:-150px -1px}.leaflet-draw-toolbar .leaflet-draw-edit-remove{background-position:-182px -2px}.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-edit-remove{background-position:-180px -1px}.leaflet-draw-toolbar .leaflet-draw-edit-edit.leaflet-disabled{background-position:-212px -2px}.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-edit-edit.leaflet-disabled{background-position:-210px -1px}.leaflet-draw-toolbar .leaflet-draw-edit-remove.leaflet-disabled{background-position:-242px -2px}.leaflet-touch .leaflet-draw-toolbar .leaflet-draw-edit-remove.leaflet-disabled{background-position:-240px -2px}.leaflet-mouse-marker{background-color:#fff;cursor:crosshair}.leaflet-draw-tooltip{background:#363636;background:rgba(0, 0, 0, 0.5);border:1px solid transparent;-webkit-border-radius:4px;border-radius:4px;color:#fff;font:12px/18px \"Helvetica Neue\", Arial, Helvetica, sans-serif;margin-left:20px;margin-top:-21px;padding:4px 8px;position:absolute;visibility:hidden;white-space:nowrap;z-index:6}.leaflet-draw-tooltip:before{border-right:6px solid black;border-right-color:rgba(0, 0, 0, 0.5);border-top:6px solid transparent;border-bottom:6px solid transparent;content:\"\";position:absolute;top:7px;left:-7px}.leaflet-error-draw-tooltip{background-color:#f2dede;border:1px solid #e6b6bd;color:#b94a48}.leaflet-error-draw-tooltip:before{border-right-color:#e6b6bd}.leaflet-draw-tooltip-single{margin-top:-12px}.leaflet-draw-tooltip-subtext{color:#f8d5e4}.leaflet-draw-guide-dash{font-size:1%;opacity:0.6;position:absolute;width:5px;height:5px}.leaflet-edit-marker-selected{background-color:rgba(254, 87, 161, 0.1);border:4px dashed rgba(254, 87, 161, 0.6);-webkit-border-radius:4px;border-radius:4px;box-sizing:content-box}.leaflet-edit-move{cursor:move}.leaflet-edit-resize{cursor:pointer}.leaflet-oldie .leaflet-draw-toolbar{border:1px solid #999}";

const DEFAULT_RANGE = '-180,-90,180,90';
const SpatialPicker = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.spatialPickerInit = createEvent(this, "spatialPickerInit", 7);
    this.valueChanged = createEvent(this, "valueChanged", 7);
    this.isInvalid = createEvent(this, "isInvalid", 7);
    this.clearSpatialInput = createEvent(this, "clearSpatialInput", 7);
    this.label = 'Select spatial area';
    this.showMapIcon = true;
    this.value = '';
    this.precision = 3;
    this.minZoom = 0;
    this.maxZoom = 24;
    this.zoom = 2;
    this.latitude = 0;
    this.longitude = 0;
    this.fitWorld = false;
    this.autocomplete = false;
    /**
     * use to enable circle draw
     */
    this.circleDraw = true;
    /**
     * use to enable marker draw
     */
    this.markerDraw = true;
    /**
     * use to disable spatial picker
     */
    this.disabled = false;
    /**
     * use spatial picker as an icon instead of default input.
     */
    this.useAsIcon = false;
    /**
     * marker icon for map
     */
    this.markerIconUrl = 'marker-icon.png';
    /**
     * marker shadow icon for map
     */
    this.markerIconShadowUrl = 'marker-shadow.png';
    /**
     * Internal State for all selected fields
     */
    this.selectedArea = DEFAULT_RANGE;
    this.selectedCircleLat = null;
    this.selectedCircleLng = null;
    this.selectedCircleRad = null;
    this.selectedCircleRadUnit = 'km';
    this.selectedMarkerLat = null;
    this.selectedMarkerLng = null;
    this.displayMap = false;
    this.invalid = false;
    /**
     * Error Message for invalid bounding box
     */
    this.errorMessage = null;
    this.selectedLayerType = 'rectangle';
    this.isNumber = function isNumber(value) {
      return typeof value === 'number' && isFinite(value);
    };
    /**
     * https://stackoverflow.com/questions/17369098/simplest-way-of-getting-the-number-of-decimals-in-a-number-in-javascript
     * @param value
     * @returns
     */
    this.countDecimals = function (value) {
      if (Math.floor(value) === value)
        return 0;
      return value.toString().split('.')[1].length || 0;
    };
    this.isLatitude = function (coord) {
      coord = Number(coord);
      return coord >= -90 && coord <= 90;
    };
    this.isLongitude = function (coord) {
      coord = Number(coord);
      return coord >= -180 && coord <= 180;
    };
    this.increasingCoordinates = function (box) {
      // make sure it's an array of numbers...
      box = box.map(Number);
      // run the check
      return box[0] >= -180 && box[0] <= 180 && box[2] >= -180 && box[2] <= 180 && box[0] <= box[2] && box[1] <= box[3];
    };
  }
  mapDrawSelectedHandler(event) {
    this.selectedLayerType = event.detail.layerType;
  }
  closeSpatialPicker(event) {
    if (this.useAsIcon) {
      if (!event.target.closest('.spatial-icon-btn')) {
        if (!this.el.querySelector('.map-wrapper').classList.contains('hide')) {
          this.el.querySelector('.map-wrapper').classList.add('hide');
        }
      }
    }
  }
  componentDidLoad() {
    this.inputEl = this.el.querySelector('gd-input');
  }
  handleMapInit(map) {
    this.map = map;
    this.map.addDrawControl();
    this.spatialPickerInit.emit(this.map);
    if (this.value) {
      if (this.isCircle(this.value)) {
        // if value is circle, set selected layer to circle
        this.selectedLayerType = 'circle';
        this.onValueChanged(this.value);
      }
      else if (this.isPoint(this.value)) {
        // if value is point, set selected layer to point
        this.selectedLayerType = 'marker';
        this.onValueChanged(this.value);
      }
      else if (typeof this.value === 'string') {
        // if value is point, set selected layer to bbox
        this.selectedLayerType = 'rectangle';
        this.onValueChanged(this.value);
      }
    }
  }
  isCircle(value) {
    return value.hasOwnProperty('lat') && value.hasOwnProperty('lng') && value.hasOwnProperty('radius') ? true : false;
  }
  isPoint(value) {
    return value.hasOwnProperty('lat') && value.hasOwnProperty('lng') && !value.hasOwnProperty('radius') ? true : false;
  }
  /**
   * function is only called when a draw is triggered from the map
   * @param bounds
   */
  handleDraw(bounds) {
    if (bounds.layerType === 'rectangle') {
      let northeast = bounds._northEast;
      let southwest = bounds._southWest;
      let box = this.map.normalizeBox([southwest.lng, southwest.lat, northeast.lng, northeast.lat]); // normalize bounding box
      let formattedValue = this.formatValueToPrecision(box.join(','), this.precision);
      this.errorMessage = this.validateBbox(formattedValue);
      this.handleSpatialAreaChanged(formattedValue); // set  all bounding box state that has changed
    }
    else if (bounds.layerType === 'circle') {
      let points = { lat: round(bounds.lat, this.precision), lng: round(bounds.lng, this.precision) };
      this.errorMessage = this.validateCircle(Object.assign(Object.assign({}, points), { radius: {
          value: round(bounds.radius, this.precision),
          unit: this.selectedCircleRadUnit,
        } }));
      // set all circle state but convert radius from metres to selected unit. Leaflet radius is always in metres
      this.handleCircleAreaChanged(Object.assign(Object.assign({}, points), { radius: { unit: this.selectedCircleRadUnit, value: ConvertUnit(bounds.radius, 'm', this.selectedCircleRadUnit) } }));
    }
    else if (bounds.layerType === 'marker') {
      let points = { lat: round(bounds.lat, this.precision), lng: round(bounds.lng, this.precision) };
      this.errorMessage = this.validatePoint(points);
      // set all marker state
      this.handleMarkerAreaChanged(points);
    }
  }
  onValueChanged(value, formatPrecision = false) {
    var _a, _b;
    try {
      if (this.selectedLayerType === 'rectangle') {
        if (!value && this.selectedArea === DEFAULT_RANGE)
          return;
        this.errorMessage = this.validateBbox(value);
        let formattedValue = formatPrecision ? this.formatValueToPrecision(value, this.precision) : value;
        this.drawSpatialArea(formattedValue);
        this.handleSpatialAreaChanged(formattedValue);
      }
      else if (this.selectedLayerType === 'circle' && this.isCircle(value)) {
        const unit = value.radius.unit;
        const radius = value.radius.value;
        const lat = value.lat;
        const lng = value.lng;
        const circle = Object.assign({}, value);
        this.errorMessage = this.validateCircle(circle);
        if ((_a = this.errorMessage) === null || _a === void 0 ? void 0 : _a.invalid)
          return;
        this.drawSpatialArea({
          lat: lat,
          lng: lng,
          radius: ConvertUnit(ConvertUnit(radius, this.selectedCircleRadUnit, unit), unit, 'm'),
        });
        this.handleCircleAreaChanged({
          lat: +lat,
          lng: +lng,
          // on handle circle state radius can reflect the changed radius unit selected
          radius: {
            unit: unit,
            value: ConvertUnit(radius, this.selectedCircleRadUnit, unit),
          },
        });
      }
      else if (this.selectedLayerType === 'marker' && this.isPoint(value)) {
        // onValueChange both lat and lng must have value to draw so using current selected value when one of the value is changed.
        const marker = {
          lat: +value.lat,
          lng: +value.lng,
        };
        this.errorMessage = this.validatePoint(marker);
        if ((_b = this.errorMessage) === null || _b === void 0 ? void 0 : _b.invalid)
          return;
        this.drawSpatialArea(marker);
        this.handleMarkerAreaChanged(marker);
      }
    }
    catch (error) {
      console.error('Failed to change value onChange ', error);
    }
  }
  handleSpatialAreaChanged(area) {
    this.selectedArea = area;
    this.valueChanged.emit(area);
  }
  handleCircleAreaChanged(circle) {
    this.selectedCircleLat = circle.lat;
    this.selectedCircleLng = circle.lng;
    this.selectedCircleRad = circle.radius.value;
    this.selectedCircleRadUnit = circle.radius.unit;
    this.valueChanged.emit(circle);
  }
  handleMarkerAreaChanged(marker) {
    this.selectedMarkerLat = marker.lat;
    this.selectedMarkerLng = marker.lng;
    this.valueChanged.emit(marker);
  }
  formatValueToPrecision(value, precision) {
    return (value &&
      value
        .split(',')
        .map(number => +parseFloat(number).toFixed(precision))
        .join(','));
  }
  drawSpatialArea(area) {
    if (!this.map || !area)
      return;
    if (this.selectedLayerType === 'rectangle') {
      let bounds = area.split(',').map(coord => +coord);
      // need 4 coordinates for a boundary
      if (bounds.length < 4)
        return;
      if (bounds[0] > bounds[2])
        bounds[2] += 360;
      this.map.drawRectangle([
        [bounds[3], bounds[2]],
        [bounds[1], bounds[0]],
      ]);
    }
    else if (this.selectedLayerType === 'circle') {
      this.map.drawCircle(area);
    }
    else if (this.selectedLayerType === 'marker') {
      this.map.drawMarker(area);
    }
  }
  showMapDisplay() {
    if (this.disabled)
      return;
    const mapContainer = this.el.querySelector('.map-wrapper');
    if (this.useAsIcon && mapContainer.classList.contains('hide')) {
      this.el.querySelector('.map-wrapper').classList.remove('hide');
      this.displayMap = true;
    }
    else {
      this.el.querySelector('.map-wrapper').classList.add('hide');
    }
  }
  showMap() {
    setTimeout(() => {
      this.map.refreshSize();
    }, 10);
  }
  resetRange() {
    this.clearSpatialInput.emit();
    this.selectedLayerType = 'rectangle';
    this.selectedCircleLat = null;
    this.selectedCircleLng = null;
    this.selectedArea = DEFAULT_RANGE;
    this.selectedCircleRad = null;
    this.selectedMarkerLat = null;
    this.selectedMarkerLng = null;
    this.errorMessage = this.validateBbox(DEFAULT_RANGE);
    this.valueChanged.emit(DEFAULT_RANGE);
  }
  validateBbox(value) {
    const errorMessages = {
      empty: 'Please enter a bounding box.',
      precision: 'Point coordinates have a maximum degree of precision of 3.',
      coord: "Bounding box contains an invalid number.'",
      range: 'Bounding box must be within -180, -90, 180, 90.',
      box: 'Bounding box must be a rectangle.',
      radiusSupported: 'Point+Radius is NOT supported by this data collection.  Please use a bounding box as your spatial extent or choose a different collection.',
    };
    const rectangle = value === null || value === void 0 ? void 0 : value.split(',');
    /**
     * @bbox bounding box
     * [south Latitude, north Latitude, west Longitude, east Longitude]
     */
    const bbox = [-180, -90, 180, 90];
    switch (true) {
      case !value:
        this.isInvalid.emit(true);
        this.clearSpatialInput.emit();
        return {
          layerType: 'rectangle',
          invalid: true,
          message: errorMessages.empty,
        };
      case rectangle.some(point => Number.isNaN(+point)):
        this.isInvalid.emit(true);
        return {
          layerType: 'rectangle',
          invalid: true,
          message: errorMessages.coord,
        };
      case rectangle.length === 4 && !(bbox[0] <= +rectangle[0] && +rectangle[0] <= bbox[2] && bbox[1] <= +rectangle[1] && +rectangle[1] <= bbox[3]):
        this.isInvalid.emit(true);
        return {
          layerType: 'rectangle',
          invalid: true,
          message: errorMessages.range,
        };
      case rectangle.length > 4 || rectangle.length < 4:
        this.isInvalid.emit(true);
        return {
          layerType: 'rectangle',
          invalid: true,
          message: errorMessages.box,
        };
      default:
        this.isInvalid.emit(false);
        return {
          layerType: 'rectangle',
          invalid: false,
          message: null,
        };
    }
  }
  validateCircle(circle) {
    const errorMessages = {
      precision: 'Point coordinates have a maximum degree of precision of 3.',
      coord: 'A Point+Radius entry is invalid (empty, not a number, or not a degree coordinate (+/-90, +/-180).',
      increasing: 'Point+Radius should not cross anti-meridian or geographical poles.',
      range: "Point+Radius must intersect {{ constraints.bbox.join(', ') }}.",
      radiusSupported: 'Point+Radius is NOT supported by this data collection.  Please use a bounding box as your spatial extent or choose a different collection.',
    };
    switch (true) {
      case !circle.lat ||
        !circle.lng ||
        !circle.radius.value ||
        !this.isNumber(+circle.lat) ||
        !this.isNumber(+circle.lng) ||
        !this.isNumber(+circle.radius.value) ||
        Math.sign(+circle.radius.value) == -1 ||
        !this.isLatitude(+circle.lat) ||
        !this.isLongitude(+circle.lng):
        this.isInvalid.emit(true);
        return {
          layerType: 'circle',
          invalid: true,
          message: errorMessages.coord,
        };
      case circle.lat && circle.lng && (this.countDecimals(+circle.lat) > 3 || this.countDecimals(+circle.lng) > 3):
        // checks the degree of accuracy is within what is supported (precision of 3) 3 decimal place.
        this.isInvalid.emit(true);
        return {
          layerType: 'circle',
          invalid: true,
          message: errorMessages.precision,
        };
      case circle.lat && circle.lng && circle.radius.value && this.increasingCoordinates([+circle.lat, +circle.lng]):
        this.isInvalid.emit(true);
        return {
          layerType: 'circle',
          invalid: true,
          message: errorMessages.increasing,
        };
      default:
        this.isInvalid.emit(false);
        return {
          layerType: 'circle',
          invalid: false,
          message: null,
        };
    }
  }
  validatePoint(point) {
    const errorMessages = {
      precision: 'Point coordinates have a maximum degree of precision of 3.',
      coord: 'A point entry is invalid (empty, not a number, or not a degree coordinate (+/-90, +/-180).',
      range: 'Point must intersect -180, -90, 180, 90.',
    };
    switch (true) {
      case !point.lat || !point.lng || !this.isNumber(point.lat) || !this.isNumber(point.lng) || !this.isNumber(point.lng):
        this.isInvalid.emit(true);
        return {
          layerType: 'marker',
          invalid: true,
          message: errorMessages.coord,
        };
      case point.lat && point.lng && (this.countDecimals(point.lat) > 3 || this.countDecimals(point.lng) > 3):
        this.isInvalid.emit(true);
        return {
          layerType: 'marker',
          invalid: true,
          message: errorMessages.precision,
        };
      case !this.isLatitude(point.lat) || !this.isLongitude(point.lng):
        this.isInvalid.emit(true);
        return {
          layerType: 'marker',
          invalid: true,
          message: errorMessages.range,
        };
      default:
        this.isInvalid.emit(false);
        return {
          layerType: 'marker',
          invalid: false,
          message: null,
        };
    }
  }
  handleCircleLatitudeChange(event) {
    var _a, _b;
    const value = {
      lat: (_b = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.target) === null || _b === void 0 ? void 0 : _b.value,
      lng: this.selectedCircleLng,
      radius: {
        unit: this.selectedCircleRadUnit,
        value: this.selectedCircleRad,
      },
    };
    this.onValueChanged(value);
  }
  handleCircleLongitudeChange(event) {
    var _a, _b;
    const value = {
      lat: this.selectedCircleLat,
      lng: (_b = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.target) === null || _b === void 0 ? void 0 : _b.value,
      radius: {
        unit: this.selectedCircleRadUnit,
        value: this.selectedCircleRad,
      },
    };
    this.onValueChanged(value);
  }
  handleCircleRadiusChange(event) {
    var _a, _b;
    const value = {
      lat: this.selectedCircleLat,
      lng: this.selectedCircleLng,
      radius: {
        unit: this.selectedCircleRadUnit,
        value: (_b = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.target) === null || _b === void 0 ? void 0 : _b.value,
      },
    };
    this.onValueChanged(value);
  }
  handleCircleUnitChange(event) {
    var _a;
    const value = {
      lat: this.selectedCircleLat,
      lng: this.selectedCircleLng,
      radius: {
        unit: (_a = event === null || event === void 0 ? void 0 : event.target) === null || _a === void 0 ? void 0 : _a.value,
        value: this.selectedCircleRad,
      },
    };
    this.onValueChanged(value);
  }
  handleMarkerLatitudeChange(event) {
    var _a, _b;
    const value = {
      lat: (_b = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.target) === null || _b === void 0 ? void 0 : _b.value,
      lng: this.selectedMarkerLng,
    };
    this.onValueChanged(value);
  }
  handleMarkerLongitudeChange(event) {
    var _a, _b;
    const value = {
      lat: this.selectedMarkerLat,
      lng: (_b = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.target) === null || _b === void 0 ? void 0 : _b.value,
    };
    this.onValueChanged(value);
  }
  handleBboxChange(event) {
    var _a, _b;
    this.selectedArea = (_b = (_a = event === null || event === void 0 ? void 0 : event.detail) === null || _a === void 0 ? void 0 : _a.target) === null || _b === void 0 ? void 0 : _b.value;
    this.onValueChanged(this.selectedArea);
  }
  renderMap() {
    return (h("gd-map", { "min-zoom": this.minZoom, "max-zoom": this.maxZoom, zoom: this.zoom, latitude: this.latitude, longitude: this.longitude, "fit-world": this.fitWorld, width: this.mapWidth, height: this.mapHeight, onMapInit: e => this.handleMapInit(e.detail), onDraw: e => this.handleDraw(e.detail), onClearDraw: () => this.onValueChanged(null), resize: this.displayMap, "draw-circle-option": this.circleDraw, "draw-marker-option": this.markerDraw, "marker-icon-url": this.markerIconUrl, "marker-icon-shadow-url": this.markerIconShadowUrl }));
  }
  renderMapContainer() {
    var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s;
    return (h("div", { class: {
        'map-wrapper': true,
        'hide': this.useAsIcon,
      } }, this.selectedLayerType === 'rectangle' ? (h("bs-form-label", { htmlFor: 'spatialpicker-bounding-box' }, "Bounding Box:")) : this.selectedLayerType === 'circle' ? (h("bs-form-label", { "aria-hidden": "true" }, "Point and Radius:")) : this.selectedLayerType === 'marker' ? (h("bs-form-label", { "aria-hidden": "true" }, "Point:")) : null, h("div", { class: "d-flex justify-content-between", style: { maxWidth: `${this.mapWidth + 18}px` } }, this.selectedLayerType === 'rectangle' ? (h("div", { class: "inline mr-0" }, h("bs-form-control", { "control-id": "spatialpicker-bounding-box", as: "input", name: "spatialpicker-bounding-box", type: "text", value: this.selectedArea, onBsInput: e => this.handleBboxChange(e), isInvalid: ((_a = this.errorMessage) === null || _a === void 0 ? void 0 : _a.invalid) && ((_b = this.errorMessage) === null || _b === void 0 ? void 0 : _b.layerType) === 'rectangle' }))) : this.selectedLayerType === 'circle' && this.circleDraw ? (h("div", { class: "inline mr-0" }, h("label", { class: "sr-only", htmlFor: "spatialpicker-point-circle-lat" }, "Latitude"), h("bs-form-control", { "control-id": "spatialpicker-point-circle-lat", as: "input", name: "spatialpicker-point-circle-lat", type: "text", value: this.selectedCircleLat, onBsInput: e => this.handleCircleLatitudeChange(e), isInvalid: ((_c = this.errorMessage) === null || _c === void 0 ? void 0 : _c.invalid) && ((_d = this.errorMessage) === null || _d === void 0 ? void 0 : _d.layerType) === 'circle', placeholder: "Latitude" }), h("label", { class: "sr-only", htmlFor: "spatialpicker-point-circle-lng" }, "Longitude"), h("bs-form-control", { "control-id": "spatialpicker-point-circle-lng", as: "input", name: "spatialpicker-point-circle-lng", type: "text", value: this.selectedCircleLng, onBsInput: e => this.handleCircleLongitudeChange(e), isInvalid: ((_e = this.errorMessage) === null || _e === void 0 ? void 0 : _e.invalid) && ((_f = this.errorMessage) === null || _f === void 0 ? void 0 : _f.layerType) === 'circle', placeholder: "Longitude" }, ' '), h("label", { class: "sr-only", htmlFor: "spatialpicker-point-circle-radius" }, "Radius"), h("bs-form-control", { "control-id": "spatialpicker-point-circle-radius", as: "input", name: "spatialpicker-point-circle-radius", type: "text", value: this.selectedCircleRad, onBsInput: e => this.handleCircleRadiusChange(e), isInvalid: ((_g = this.errorMessage) === null || _g === void 0 ? void 0 : _g.invalid) && ((_h = this.errorMessage) === null || _h === void 0 ? void 0 : _h.layerType) === 'circle', placeholder: "Radius" }, ' '), h("label", { class: "sr-only", htmlFor: "spatialpicker-point-circle-unit" }, "Units"), h("select", { name: "spatialpicker-point-circle-unit", id: "spatialpicker-point-circle-unit", onInput: e => {
        this.handleCircleUnitChange(e);
      }, class: {
        'spatial-form-select': true,
        'border border-danger': ((_j = this.errorMessage) === null || _j === void 0 ? void 0 : _j.invalid) && ((_k = this.errorMessage) === null || _k === void 0 ? void 0 : _k.layerType) === 'circle',
      } }, h("option", { value: "km", selected: this.selectedCircleRadUnit === 'km' }, "km"), h("option", { value: "m", selected: this.selectedCircleRadUnit === 'm' }, "m"), h("option", { value: "mi", selected: this.selectedCircleRadUnit === 'mi' }, "mi"), h("option", { value: "deg", selected: this.selectedCircleRadUnit === 'deg' }, "deg"), h("option", { value: "rad", selected: this.selectedCircleRadUnit === 'rad' }, "rad")))) : this.selectedLayerType === 'marker' && this.markerDraw ? (h("div", { class: "inline", style: { maxWidth: '300px' } }, h("label", { class: "sr-only", htmlFor: "spatialpicker-point-marker-lat" }, "Marker's Latitude"), h("bs-form-control", { "control-id": "spatialpicker-point-marker-lat", as: "input", name: "spatialpicker-point-marker-lat", type: "text", value: this.selectedMarkerLat, onBsInput: e => this.handleMarkerLatitudeChange(e), isInvalid: ((_l = this.errorMessage) === null || _l === void 0 ? void 0 : _l.invalid) && ((_m = this.errorMessage) === null || _m === void 0 ? void 0 : _m.layerType) === 'marker', placeholder: "Latitude" }), h("label", { class: "sr-only", htmlFor: "spatialpicker-point-marker-lng" }, "Marker's Longitude"), h("bs-form-control", { "control-id": "spatialpicker-point-marker-lng", as: "input", name: "spatialpicker-point-marker-lng", type: "text", value: this.selectedMarkerLng, onBsInput: e => this.handleMarkerLongitudeChange(e), isInvalid: ((_o = this.errorMessage) === null || _o === void 0 ? void 0 : _o.invalid) && ((_p = this.errorMessage) === null || _p === void 0 ? void 0 : _p.layerType) === 'marker', placeholder: "Longitude" }))) : null, this.useAsIcon && (h("div", { "data-test": "btn-default-range", class: "reset-range" }, h("bs-button", { onClick: () => this.resetRange() }, "Default Range")))), ((_q = this.errorMessage) === null || _q === void 0 ? void 0 : _q.invalid) && ((_r = this.errorMessage) === null || _r === void 0 ? void 0 : _r.layerType) === this.selectedLayerType && (h("span", { class: "text-danger d-block mb-3" }, (_s = this.errorMessage) === null || _s === void 0 ? void 0 : _s.message)), h("div", { class: "mt-3 map-container" }, this.renderMap()), h("p", { class: "mb-0" }, "Available Range: -180, -90, 180, 90")));
  }
  render() {
    return (h(Host, { class: {
        'spatial-icon-btn': this.useAsIcon,
      } }, this.useAsIcon ? (h("div", { class: "spatial-btn-wrapper" }, h("bs-button", { class: "spatial-button", variant: "light", disabled: this.disabled, title: this.label, onClick: () => this.showMapDisplay() }, h("bs-icon", { icon: "fas fa-map", size: 20 })), this.renderMapContainer())) : (h("div", null, this.renderMapContainer()))));
  }
  get el() { return getElement(this); }
};
SpatialPicker.style = gdSpatialPickerCss;

export { SpatialPicker as gd_spatial_picker };
