/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as f } from "../../chunks/runtime.js";
import { ref as u } from "lit/directives/ref.js";
import { css as b, html as y } from "lit";
import { u as _ } from "../../chunks/useT9n.js";
import { LitElement as T } from "@arcgis/lumina";
import "../layer-table/customElement.js";
const v = b`.height-51{height:51px}.width-51{width:51px}`;
class C extends T {
  constructor() {
    super(), this._translations = _({ name: "field-selection", blocking: !0 }), this._fieldSortOrder = "default", this._selectedFields = [], this._fieldVisibilityPopoverClickHandler = (e) => {
      this._fieldVisibilityPopoverNode ? this._isInNode(e.target, "arcgis-field-pick-list") || (document.body.removeChild(this._fieldVisibilityPopoverNode), this._fieldVisibilityPopoverNode = void 0, document.removeEventListener("click", this._fieldVisibilityPopoverClickHandler)) : document.removeEventListener("click", this._fieldVisibilityPopoverClickHandler);
    }, this.listenOn(window, "columnReorder", this.handleColumnReorder, { capture: !0 });
  }
  static {
    this.properties = { configExtraFields: 1, layer: 0, mapView: 0, table: 0, tableRef: 0, _translations: 16 };
  }
  static {
    this.styles = v;
  }
  render() {
    return y`<calcite-action alignment=center class="height-51 width-51" id=solutions-field-selection .text=${this._translations.fieldVisibility} scale=m @click=${() => this._handleFieldVisibilityClick()} @mouseover=${() => this._addTableTooltip(this._fieldVisibilityActionNode, this._translations.fieldVisibility)} @mouseout=${() => this._removeTableTooltip()} @focus=${() => this._addTableTooltip(this._fieldVisibilityActionNode, this._translations.fieldVisibility)} ${u((e) => this._fieldVisibilityActionNode = e)}><calcite-icon aria-hidden=true scale=s icon=gear></calcite-icon></calcite-action>`;
  }
  handleColumnReorder() {
    this._fieldSortOrder = "default", this._fieldVisibilityPopoverNode && (this.removeFieldsPickList(), this._handleFieldVisibilityClick());
  }
  _handleFieldVisibilityClick() {
    if (this._fieldVisibilityPopoverNode)
      return;
    const e = this.table?.tableTemplate?.columnTemplates;
    if (this.layer && this.mapView && e && this._fieldVisibilityActionNode) {
      document.removeEventListener("click", this._fieldVisibilityPopoverClickHandler);
      const t = this.table.fieldColumns.map((l) => ({
        alias: l.field.alias,
        description: l.field.description,
        name: l.field.name,
        type: l.field.type
      }));
      if (this._hasAttachmentsEnabled(this.layer)) {
        const l = "Attachments";
        if (this._shouldShowField(l.toUpperCase(), !1)) {
          if (!e.some((a) => a.fieldName.toUpperCase() === l.toUpperCase())) {
            const a = {
              fieldName: l,
              type: "attachment",
              visible: !0
            };
            e.push(a);
          }
          t.push({
            name: l,
            alias: "Photos and files",
            type: "none",
            description: l
          });
        }
      }
      if (this.table.relatedRecordsEnabled && this.layer.relationships && this.layer.relationships.length > 0) {
        const l = this.layer.parent;
        this.layer.relationships.forEach((a, p) => {
          let o, n = this._shouldShowField(a.name || "", !0);
          if (!n) {
            const c = [...l?.layers || [], ...l?.tables || []].find((h) => h.layerId === a.relatedTableId), d = c ? c.title : void 0;
            d && this._shouldShowField(d, !0) && (a.name = d, n = !0);
          }
          if (!n) {
            const r = a.keyField || `related_${p}`;
            this._shouldShowField(r, !0) && (a.name = a.name || r, n = !0);
          }
          if (!e.some((r) => r.fieldName.toLowerCase() === a.name?.toLowerCase() ? (o = a.name, !0) : !1))
            if (a.name) {
              o = a.name;
              const r = {
                fieldName: o,
                type: "relationship",
                visible: !0
              };
              n = this._shouldShowField(o, !0), e.push(r);
            } else {
              const r = [...l?.layers || [], ...l?.tables];
              let c;
              if (r.some((d) => d.layerId === a.relatedTableId ? (c = d, !0) : !1), c) {
                o = c.title, a.name = o;
                const d = {
                  fieldName: o,
                  type: "relationship",
                  visible: !0
                };
                n = this._shouldShowField(o, !0), e.push(d);
              }
            }
          o && n && t.push({
            name: o,
            alias: `Related ${o}`,
            type: "none",
            description: `related:${o}`
          });
        });
      }
      const i = this._fieldVisibilityPopoverNode ? this._fieldVisibilityPopoverNode : document.createElement("arcgis-field-pick-list");
      i.layer = this.layer, i.fields = t, i.showFieldInfo = !0, i.showFieldName = !0, i.showDescription = !1, i.showSelectionAll = !0, i.hideCancel = !0, i.hideSort = !1, i.showFilterLength = 5, i.multiple = !0, i.heading = this._translations.fieldVisibility, i.okBtnText = this._translations.doneWithFieldChanges, i.filterPlaceholderText = this._translations.filterFields, i.sortBy = this._fieldSortOrder ?? "default";
      const m = this.table?.visibleColumns.map((l) => l.fieldName.startsWith("EsriFeatureTableRelationshipColumn") || l.fieldName.startsWith("EsriFeatureTableAttachmentsColumn") ? l.effectiveLabel : l.fieldName);
      i.selectedFields = e.reduce((l, a) => ((m ? m.indexOf(a.fieldName) > -1 : a.visible) && l.push(a.fieldName), l), []), this._selectedFields = i.selectedFields, i.style.minHeight = "340px", i.popoverProps = {
        refElement: this._fieldVisibilityActionNode,
        popoverWidth: 300,
        placement: "bottom-end",
        offsetDistance: -20,
        triggerDisabled: !1,
        autoClose: !1
      }, i.addEventListener("arcgisChange", (l) => {
        l.stopPropagation();
        const a = l.detail.selectedFields, p = this._getDifference(a, this._selectedFields), o = this._getDifference(this._selectedFields, a);
        p.concat(o).forEach((r) => {
          const c = this.layer?.relationships?.map((d) => d.name) || [];
          if (r === "Attachments") {
            const d = this.table.columns.find((h) => "onShowAttachments" in h);
            d.hidden = o.indexOf(r) > -1;
          } else c.indexOf(r) > -1 ? this.table.columns.filter((h) => "relationshipId" in h).forEach((h) => {
            o.indexOf(r) > -1, r == h.effectiveLabel && (h.hidden = o.indexOf(r) > -1);
          }) : this.table.toggleColumnVisibility(r);
        }), this._selectedFields = a, this._updateTable(this.table.tableTemplate);
      }), i.addEventListener("arcgisSortByChange", (l) => {
        l.stopPropagation(), this._fieldSortOrder = l.detail, this._sortFields(l.detail);
      }), i.addEventListener("arcgisClose", () => {
        this._closePopovers(), setTimeout(() => this._fieldVisibilityActionNode.setFocus(), 200);
      }), document.body.appendChild(i), this._fieldVisibilityPopoverNode = i, setTimeout(() => document.addEventListener("click", this._fieldVisibilityPopoverClickHandler), 200);
    }
  }
  _shouldShowField(e, t) {
    return (this.configExtraFields || []).some((s) => t ? s.replace("related:", "").toUpperCase() === e.toUpperCase() : s.toUpperCase() === e.toUpperCase());
  }
  removeFieldsPickList() {
    this._fieldVisibilityPopoverNode && (document.body.removeChild(this._fieldVisibilityPopoverNode), this._fieldVisibilityPopoverNode = void 0);
  }
  _sortFields(e) {
    const t = this.table.tableTemplate.columnTemplates, s = this._getSortOrder(e), m = t.filter((a) => a.type !== "attachment" && a.type !== "relationship").sort((a, p) => {
      const o = s.indexOf(a.fieldName), n = s.indexOf(p.fieldName);
      return o === -1 && n !== -1 ? 1 : o !== -1 && n === -1 ? -1 : o === -1 && n === -1 ? 0 : o - n;
    }), l = t.filter((a) => a.type === "attachment" || a.type === "relationship");
    this.tableRef.setColumnOrder([...m, ...l]), this._updateTable(this.table.tableTemplate);
  }
  _getSortOrder(e) {
    const t = [...this.layer.fields];
    return e === "display" ? t.sort((s, i) => s.alias.localeCompare(i.alias)) : e === "field" ? t.sort((s, i) => s.name.localeCompare(i.name)) : e === "type" && t.sort((s, i) => s.type.localeCompare(i.type)), t.map((s) => s.name);
  }
  _getDifference(e, t) {
    return e.filter((s) => !t.includes(s));
  }
  _updateTable(e) {
    this.table.tableTemplate = e, this._isStandardView() && this._syncAttributeTableTemplate();
  }
  async _syncAttributeTableTemplate() {
    const e = this.table.layer;
    if (e.attributeTableTemplate) {
      const { _modules: t } = this, s = e.attributeTableTemplate.clone();
      t?.attributeTableTemplateUtils.syncAttributeTableTemplate(this.table, s), JSON.stringify(s) !== JSON.stringify(e.attributeTableTemplate) && (e.attributeTableTemplate = s);
    }
    if (e.attributeTableTemplate?.orderByFields?.length > 1) {
      const t = e.attributeTableTemplate.clone(), s = this.table.activeSortOrders[0];
      t.orderByFields = [
        { field: s.fieldName, order: s.direction }
      ], e.attributeTableTemplate = t, this._syncColumnDirectionsWithOrderByFields();
    }
  }
  _syncColumnDirectionsWithOrderByFields() {
    const e = this.table.activeSortOrders[0]?.fieldName;
    this.table.columns.forEach((t) => {
      "fieldName" in t && t.fieldName !== e && (t.direction = void 0);
    }), this.table.tableTemplate?.columnTemplates.forEach((t) => {
      "fieldName" in t && t.fieldName !== e && (t.direction = void 0);
    });
  }
  _isStandardView() {
    return !this.table.relatedTable && !this.table.attachmentsViewOptions.objectId;
  }
  _closePopovers() {
    document.removeEventListener("click", this._fieldVisibilityPopoverClickHandler), this._fieldVisibilityPopoverNode && (document.body.removeChild(this._fieldVisibilityPopoverNode), this._fieldVisibilityPopoverNode = void 0);
  }
  _addTableTooltip(e, t) {
    const s = document.createElement("calcite-tooltip");
    s.className = "table-tooltip", s.referenceElement = e, s.placement = "trailing-start", s.open = !0;
    const i = document.createElement("div");
    i.className = "tooltip", i.innerHTML = t, s.append(i), document.body.append(s);
  }
  _removeTableTooltip() {
    document.querySelectorAll(".table-tooltip").forEach((e) => e.parentNode?.removeChild(e));
  }
  _isInNode(e, t) {
    for (; e; ) {
      if (e.nodeName === t.toUpperCase())
        return !0;
      e = e.parentElement;
    }
    return !1;
  }
  _hasAttachmentsEnabled(e) {
    if (!e?.capabilities)
      return !1;
    const { capabilities: { data: { supportsAttachment: t }, operations: { supportsQueryAttachments: s } } } = e;
    return t && s;
  }
}
f("field-selection", C);
export {
  C as FieldSelection
};
