/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as w } from "../../chunks/runtime.js";
import { c as m, i as g, j as I } from "../../chunks/mapViewUtils.js";
import { d as v } from "../../chunks/queryUtils.js";
import { u as k } from "../../chunks/useT9n.js";
import { createRef as u, ref as S } from "lit-html/directives/ref.js";
import { LitElement as L, createEvent as y, noShadowRoot as E, safeClassMap as G } from "@arcgis/lumina";
import { css as x, html as h } from "lit";
import { useContextConsumer as $ } from "@arcgis/lumina/context";
import { p as D } from "../../chunks/publicNotificationContext.js";
import C from "@arcgis/core/Graphic.js";
import A from "@arcgis/core/layers/GraphicsLayer.js";
const O = x`@layer{:host{display:block}.div-not-visible{display:none!important}.border{outline:1px solid var(--calcite-color-border-input)}.esri-sketch{display:flex;flex-flow:column wrap}.esri-widget{box-sizing:border-box;color:#323232;font-size:14px;font-family:Avenir Next,Helvetica Neue,Helvetica,Arial,sans-serif;line-height:1.3em;background-color:var(--calcite-color-surface-2)}.esri-sketch__panel{align-items:center;display:flex;flex-flow:row nowrap;padding:0}.esri-sketch__tool-section{border-right:1px solid rgba(110,110,110,.3)}.esri-sketch__section{align-items:center;display:flex;flex-flow:row nowrap;padding:0 7px;margin:6px 0;border-right:1px solid rgba(110,110,110,.3)}.display-flex{display:flex}.font-bold{font-weight:700}.width-full{width:100%}.label-margin-0{--calcite-label-margin-bottom: 0}.padding-start-1-2{padding-inline-start:.5rem}.font-weight-500{font-weight:500}.word-wrap-anywhere{word-wrap:anywhere}.tooltip-message{padding:5px 8px;font-weight:var(--calcite-font-weight-normal);color:var(--calcite-color-text-2);max-width:400px}}`;
class R extends L {
  constructor() {
    super(), this.enabledLayerIds = [], this.enableSearchDistance = !0, this.enableSearchDistanceOnLoad = !1, this.searchDistanceEnabled = !1, this.selectionSets = [], this.bufferColor = [227, 139, 79, 0.8], this.bufferOutlineColor = [255, 255, 255], this.geometries = [], this.drawnGraphicsArr = [], this._translations = k({ name: "refine-selection", blocking: !0 }), this._selectionMode = "ADD", this._addEnabled = !0, this._drawTools = u(), this._enabledLayerIds = [], this._layerPicker = u(), this._featuresCollection = {}, this._pnContextConsumer = $({
      context: D,
      subscribe: !0
    }), this._bufferTools = u(), this._undoGraphicsArr = [], this.selectionLoadingChange = y(), this.selectionSetsChanged = y(), this.listenOn(window, "distanceChanged", this.distanceChanged), this.listenOn(window, "unitChanged", this.unitChanged);
  }
  static {
    this.properties = { addresseeLayer: 0, enabledLayerIds: 0, enableSearchDistance: 5, enableSearchDistanceOnLoad: 5, mapView: 0, searchDistanceEnabled: 5, selectionSets: 0, sketchLineSymbol: 0, sketchPointSymbol: 0, sketchPolygonSymbol: 0, defaultBufferUnit: 1, bufferColor: 1, bufferOutlineColor: 1, defaultBufferDistance: 9, geometries: 0, drawnGraphicsArr: 0, _translations: 16, _selectionMode: 16, _refineLayer: 16 };
  }
  static {
    this.styles = O;
  }
  static {
    this.shadowRootOptions = E;
  }
  willUpdate(e) {
    e.has("defaultBufferUnit") && this.hasUpdated && this._refineSelectionSet && (this._refineSelectionSet.unit = this.defaultBufferUnit), e.has("defaultBufferDistance") && this.hasUpdated && this._refineSelectionSet && (this._refineSelectionSet.distance = this.defaultBufferDistance);
  }
  async distanceChanged(e) {
    e.detail.newValue !== e.detail.oldValue && this._refineSelectionSet && (this._refineSelectionSet.distance = e.detail.newValue);
  }
  async unitChanged(e) {
    e.detail.newValue !== e.detail.oldValue && this._refineSelectionSet && (this._refineSelectionSet.unit = e.detail.newValue);
  }
  async load() {
    this._enabledLayerIds = this._getEnabledLayerIds(), await this._setRefineSet(this._enabledLayerIds[0]), this._undoGraphicsArr = this._refineSelectionSet?.undoGraphicsArr;
  }
  async loaded() {
    await this._init();
  }
  render() {
    const e = this._enabledLayerIds.length > 1 ? "display-block" : "display-none";
    return h`<div class=${`${e} padding-top-sides-1`}><div class="display-flex"><calcite-label class="font-bold width-full label-margin-0"><div class="display-flex">${this._translations.inputLayer}<calcite-icon aria-hidden=true class="padding-start-1-2 icon" .flipRtl=${this._translations._lang?.toLowerCase() !== "he"} icon=question id=refine-input-layer scale=s></calcite-icon></div><map-layer-picker .enabledLayerIds=${this._enabledLayerIds} .mapView=${this.mapView} @layerSelectionChange=${(t) => {
      this._layerSelectionChange(t);
    }} .selectedIds=${this._refineLayer ? [this._refineLayer.layer.id] : []} ${S(this._layerPicker)}></map-layer-picker></calcite-label><calcite-popover closable label overlay-positioning=fixed reference-element=refine-input-layer><span class="tooltip-message">${this._translations.inputLayerTip}</span></calcite-popover></div></div><div class="padding-1"><div class="padding-bottom-1"><calcite-segmented-control class="w-100" width=full><calcite-segmented-control-item .checked=${this._addEnabled} class="w-50 word-wrap-anywhere" .iconStart=${this._selectionMode === "ADD" ? "check" : void 0} @click=${() => this._setSelectionMode("ADD")} value=ADD><span class="font-weight-500">${this._translations.add}</span></calcite-segmented-control-item><calcite-segmented-control-item .checked=${!this._addEnabled} class="w-50 word-wrap-anywhere" .iconStart=${this._selectionMode === "REMOVE" ? "check" : void 0} @click=${() => this._setSelectionMode("REMOVE")} value=REMOVE><span class="font-weight-500">${this._translations.remove}</span></calcite-segmented-control-item></calcite-segmented-control></div><div><map-draw-tools active draw-mode=REFINE .mapView=${this.mapView} @drawRedo=${() => this._redo()} @drawUndo=${() => this._undo()} @sketchGraphicsChange=${this._sketchGraphicsChanged} .pointSymbol=${this.sketchPointSymbol} .polygonSymbol=${this.sketchPolygonSymbol} .polylineSymbol=${this.sketchLineSymbol} .redoEnabled=${this._refineSelectionSet?.redoStack && this._refineSelectionSet.redoStack.length > 0} .undoEnabled=${this._refineSelectionSet?.undoStack && this._refineSelectionSet.undoStack.length > 0} ${S(this._drawTools)}></map-draw-tools></div>${this.enableSearchDistance ? this._getBufferOptions() : void 0}<br>${h`<calcite-list class="list-border" label>${this._getRefineSelectionSetList()}</calcite-list>`}</div>`;
  }
  async _init() {
    this._initGraphicsLayer();
  }
  _initGraphicsLayer() {
    const e = this._translations.bufferLayer;
    if (this.mapView) {
      const t = this.mapView.map.layers.findIndex((i) => i.title === e);
      if (t > -1)
        this._bufferGraphicsLayer = this.mapView.map.layers.getItemAt(t);
      else if (this._bufferGraphicsLayer = new A({ title: e, listMode: "hide" }), this._bufferGraphicsLayer) {
        const i = this.mapView.map.layers.findIndex((s) => s.title === this._translations.sketchLayer);
        i > -1 ? this.mapView.map.layers.add(this._bufferGraphicsLayer, i) : this.mapView.map.layers.add(this._bufferGraphicsLayer);
      }
    }
  }
  _layerSelectionChange(e) {
    const t = e.detail[0];
    this._setRefineSet(t);
  }
  _setSelectionMode(e) {
    this._selectionMode = e;
  }
  async _sketchGraphicsChanged(e) {
    const t = e.detail?.graphics[0], i = t.geometry;
    this.geometries = [i];
    const s = await this._selectFeatures(i);
    if (this._sketchGraphic = t, this._refineSelectionSet?.distance === 0 && s.length > 0) {
      const a = { drawnGraphic: t, bufferGraphic: void 0 };
      this.drawnGraphicsArr.push(a);
    }
  }
  _getEnabledLayerIds() {
    return this.selectionSets.reduce((e, t) => {
      const i = t?.layerView?.layer.id;
      return i && e.indexOf(i) < 0 ? e.push(i) : t.workflowType === "REFINE" && Object.keys(t.refineInfos).forEach((s) => {
        e.indexOf(s) < 0 && e.push(s);
      }), e;
    }, []);
  }
  async _setRefineSet(e) {
    this.selectionSets.some((t) => t.workflowType === "REFINE" ? (this._refineSelectionSet = t, Object.keys(t.refineInfos).indexOf(e) > -1) : !1) || await this._initRefineSet(e, this._refineSelectionSet), this._refineSelectionSet && (this._refineLayer = this._refineSelectionSet.refineInfos[e].layerView);
  }
  async _initRefineSet(e, t) {
    const i = {};
    i[e] = {
      addIds: [],
      removeIds: [],
      layerView: this.mapView && await m(this.mapView, e)
    }, t ? t.refineInfos = { ...t.refineInfos, ...i } : (this._refineSelectionSet = {
      id: Date.now(),
      searchResult: void 0,
      buffer: void 0,
      distance: this.defaultBufferDistance || 0,
      download: !0,
      unit: this.defaultBufferUnit || "feet",
      label: "Refine",
      selectedIds: [],
      layerView: this.mapView && await m(this.mapView, e),
      geometries: [],
      graphics: [],
      selectLayers: [],
      workflowType: "REFINE",
      searchDistanceEnabled: !1,
      useLayerFeaturesEnabled: !1,
      refineInfos: i,
      redoStack: [],
      undoStack: [],
      sketchGraphic: void 0,
      undoGraphicsArr: []
    }, this.selectionSets.push(this._refineSelectionSet));
  }
  _undo() {
    if (this._refineSelectionSet) {
      const e = this._refineSelectionSet.undoStack && this._refineSelectionSet.undoStack.pop();
      if (e) {
        if (this.drawnGraphicsArr.length > 0) {
          const t = this.drawnGraphicsArr.pop();
          t && this._refineSelectionSet.undoGraphicsArr?.push(t), this._undoGraphicsArr.push(t);
        }
        this._refineSelectionSet.redoStack && this._updateIds(e.ids, e.mode === "ADD" ? "REMOVE" : "ADD", this._refineSelectionSet.redoStack, e.layerView);
      }
    }
  }
  _redo() {
    if (this._refineSelectionSet) {
      const e = this._refineSelectionSet.redoStack && this._refineSelectionSet.redoStack.pop();
      if (e) {
        if (this._undoGraphicsArr.length > 0) {
          const t = this._undoGraphicsArr.pop();
          this._refineSelectionSet.undoGraphicsArr?.pop(), t && this.drawnGraphicsArr.push(t);
        }
        this._refineSelectionSet.undoStack && this._updateIds(e.ids, e.mode === "ADD" ? "REMOVE" : "ADD", this._refineSelectionSet.undoStack, e.layerView);
      }
    }
  }
  _getBufferOptions() {
    this.enableSearchDistanceOnLoad && this._refineSelectionSet && (this._refineSelectionSet.searchDistanceEnabled = !0, this.searchDistanceEnabled = !0, this.enableSearchDistanceOnLoad = !1);
    const e = this._refineSelectionSet?.searchDistanceEnabled ? "search-distance" : "div-not-visible";
    return h`<div><div class="padding-top-1 display-flex"><calcite-label class="label-margin-0 w-100" layout=inline-space-between><div class="tooltip-container">${this._translations.searchDistance}<calcite-icon class="padding-start-1-2 icon" .flipRtl=${this._translations._lang?.toLowerCase() !== "he"} icon=question id=search-distance-icon scale=s></calcite-icon></div></calcite-label><calcite-popover closable label overlay-positioning=fixed reference-element=search-distance-icon><span class="tooltip-message">${this._translations.useSearchDistanceTootip}</span></calcite-popover><calcite-switch .checked=${this._refineSelectionSet?.searchDistanceEnabled} @calciteSwitchChange=${() => {
      this.searchDistanceEnabled = !this.searchDistanceEnabled, this._refineSelectionSet && (this._refineSelectionSet.searchDistanceEnabled = this.searchDistanceEnabled);
    }}></calcite-switch></div><div class=${G(e)}><buffer-tools .disabled=${!this.searchDistanceEnabled} .distance=${this._refineSelectionSet?.distance} .geometries=${this.geometries} @bufferComplete=${(t) => {
      this._bufferComplete(t);
    }} .unit=${this._refineSelectionSet?.unit} ${S(this._bufferTools)}></buffer-tools></div></div>`;
  }
  async _bufferComplete(e) {
    if (this._bufferGeometry = Array.isArray(e.detail) ? e.detail[0] : e.detail, this._bufferGeometry) {
      const t = {
        type: "simple-fill",
        color: this.bufferColor,
        outline: {
          color: this.bufferOutlineColor,
          width: 1
        }
      }, i = new C({
        geometry: this._bufferGeometry,
        symbol: t
      });
      if (this._bufferGraphicsLayer && i && this.mapView && (this._bufferGraphicsLayer.removeAll(), this._bufferGraphicsLayer.add(i), (await this._selectFeatures(this._bufferGeometry)).length > 0)) {
        const a = { drawnGraphic: this._sketchGraphic, bufferGraphic: i };
        this.drawnGraphicsArr.push(a);
      }
    } else
      this._bufferGraphicsLayer && this._bufferGraphicsLayer.removeAll();
  }
  _getRefineSelectionSetList() {
    const e = this._getTotal(this.selectionSets);
    let t;
    this.selectionSets.some((l) => l.workflowType === "REFINE" ? (t = l, !0) : !1);
    let i = 0, s = 0;
    t?.refineInfos && Object.keys(t.refineInfos).forEach((l) => {
      i += t.refineInfos[l].addIds.length, s += t.refineInfos[l].removeIds.length;
    });
    const a = this._translations.featuresAdded, f = this._translations.featuresRemoved, c = this._translations.totalSelected;
    return [
      h`<calcite-list-item .label=${a.replace("{{n}}", i.toString())}></calcite-list-item>`,
      h`<calcite-list-item .label=${f.replace("{{n}}", s.toString())}></calcite-list-item>`,
      h`<calcite-list-item .label=${c.replace("{{n}}", e.toString())}></calcite-list-item>`
    ];
  }
  _getTotal(e) {
    const t = g(e);
    return Object.keys(t).reduce((i, s) => {
      const a = t[s];
      return i += a.ids.length, i;
    }, 0);
  }
  async _selectFeatures(e) {
    this.selectionLoadingChange.emit(!0);
    let t = [];
    if (this._refineLayer) {
      this._featuresCollection[this._refineLayer?.layer.id] = [];
      const i = await v(0, this._refineLayer?.layer, e, this._featuresCollection);
      this.selectionLoadingChange.emit(!1);
      let s = [];
      Object.keys(i).forEach((a) => {
        a === this._refineLayer?.layer.id && (s = s.concat(i[a]));
      }), t = Array.isArray(s) ? s.map((a) => a.attributes[a?.layer?.objectIdField]) : [], this._refineSelectionSet?.undoStack && await this._updateIds(t, this._selectionMode, this._refineSelectionSet.undoStack, this._refineLayer), this._bufferGraphicsLayer && this._refineSelectionSet && this._refineSelectionSet.distance > 0 && (await new Promise((a) => setTimeout(a, 1e3)), this._bufferGraphicsLayer.removeAll()), this.geometries = [], this._drawTools.value && this._drawTools.value.clear();
    }
    return t;
  }
  async _highlightFeatures() {
    const e = this._pnContextConsumer.value;
    e.removeHandles(), e.highlightHandles = await I(this.selectionSets);
  }
  async _updateIds(e, t, i, s) {
    let a = !1;
    const f = this._refineSelectionSet?.refineInfos, c = s.layer.id, l = {};
    l[c] = {
      addIds: [],
      removeIds: [],
      layerView: s
    };
    const n = f && Object.keys(f).indexOf(c) > -1 ? f[c] : l[c];
    if (t === "ADD")
      n.addIds = [.../* @__PURE__ */ new Set([...e, ...n.addIds])], n.addIds.length > 0 && i.push({
        ids: e,
        mode: t,
        layerView: s
      }), n.removeIds.length > 0 && (n.removeIds = n.removeIds.filter((p) => e.indexOf(p) < 0));
    else {
      const p = this.selectionSets.reduce((o, r) => (e.forEach((d) => {
        r.workflowType !== "REFINE" ? r.selectedIds.indexOf(d) > -1 && o.push(d) : Object.keys(r.refineInfos).some((b) => {
          const _ = r.refineInfos[b];
          return _.layerView.layer.id === s.layer.id && _.addIds.indexOf(d) > -1 ? (o.push(d), !0) : !1;
        });
      }), o), []);
      n.removeIds = [.../* @__PURE__ */ new Set([...p, ...n.removeIds])], n.addIds = n.addIds.filter((o) => p.indexOf(o) < 0), n.removeIds.length > 0 && i.push({
        ids: p,
        mode: t,
        layerView: s
      }), this.selectionSets = this.selectionSets.reduce((o, r) => (r.workflowType !== "REFINE" && r.layerView.layer.id === s.layer.id ? (r.selectedIds = r.selectedIds.filter((d) => n.removeIds.indexOf(d) < 0), r.selectedIds.length > 0 ? o.push(r) : a = !0) : o.push(r), o), []);
    }
    this._refineSelectionSet && (this._refineSelectionSet.refineInfos[c] = n), this.selectionSets = [...this.selectionSets], a && this.selectionSetsChanged.emit(this.selectionSets), await this._highlightFeatures();
  }
}
w("refine-selection", R);
export {
  R as RefineSelection
};
