/* COPYRIGHT Esri - https://js.arcgis.com/1.2/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 appearance=solid 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 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((s) => ({
        alias: s.field.alias,
        description: s.field.description,
        name: s.field.name,
        type: s.field.type
      }));
      if (this._hasAttachmentsEnabled(this.layer)) {
        const s = "Attachments";
        if (this._shouldShowField(s.toUpperCase(), !1)) {
          if (!e.some((o) => o.fieldName.toUpperCase() === s.toUpperCase())) {
            const o = {
              fieldName: s,
              type: "attachment",
              visible: !0
            };
            e.push(o);
          }
          t.push({
            name: s,
            alias: "Photos and files",
            type: "none",
            description: s
          });
        }
      }
      if (this.table.relatedRecordsEnabled && this.layer.relationships && this.layer.relationships.length > 0) {
        const s = this.layer.parent;
        this.layer.relationships.forEach((o) => {
          let a, r = this._shouldShowField(o.name || "", !0);
          if (!e.some((n) => n.fieldName.toLowerCase() === o.name?.toLowerCase() ? (a = o.name, !0) : !1))
            if (o.name) {
              a = o.name;
              const n = {
                fieldName: a,
                type: "relationship",
                visible: !0
              };
              r = this._shouldShowField(a, !0), e.push(n);
            } else {
              const n = [...s?.layers || [], ...s?.tables];
              let d;
              if (n.some((c) => c.layerId === o.relatedTableId ? (d = c, !0) : !1), d) {
                a = d.title, o.name = a;
                const c = {
                  fieldName: a,
                  type: "relationship",
                  visible: !0
                };
                r = this._shouldShowField(a, !0), e.push(c);
              }
            }
          a && r && t.push({
            name: a,
            alias: `Related ${a}`,
            type: "none",
            description: `related:${a}`
          });
        });
      }
      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 p = this.table?.visibleColumns.map((s) => s.fieldName.startsWith("EsriFeatureTableRelationshipColumn") || s.fieldName.startsWith("EsriFeatureTableAttachmentsColumn") ? s.effectiveLabel : s.fieldName);
      i.selectedFields = e.reduce((s, o) => ((p ? p.indexOf(o.fieldName) > -1 : o.visible) && s.push(o.fieldName), s), []), 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", (s) => {
        s.stopPropagation();
        const o = s.detail.selectedFields, a = this._getDifference(o, this._selectedFields), r = this._getDifference(this._selectedFields, o);
        a.concat(r).forEach((d) => {
          const c = this.layer?.relationships?.map((m) => m.name) || [];
          if (d === "Attachments") {
            const m = this.table.columns.find((h) => "onShowAttachments" in h);
            m.hidden = r.indexOf(d) > -1;
          } else c.indexOf(d) > -1 ? this.table.columns.filter((h) => "relationshipId" in h).forEach((h) => {
            r.indexOf(d) > -1, d == h.effectiveLabel && (h.hidden = r.indexOf(d) > -1);
          }) : this.table.toggleColumnVisibility(d);
        }), this._selectedFields = o, this._updateTable(this.table.tableTemplate);
      }), i.addEventListener("arcgisSortByChange", (s) => {
        s.stopPropagation(), this._fieldSortOrder = s.detail, this._sortFields(s.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((l) => t ? l.replace("related:", "").toUpperCase() === e.toUpperCase() : l.toUpperCase() === e.toUpperCase());
  }
  removeFieldsPickList() {
    this._fieldVisibilityPopoverNode && (document.body.removeChild(this._fieldVisibilityPopoverNode), this._fieldVisibilityPopoverNode = void 0);
  }
  _sortFields(e) {
    const t = this.table.tableTemplate.columnTemplates, l = this._getSortOrder(e), p = t.filter((o) => o.type !== "attachment" && o.type !== "relationship").sort((o, a) => {
      const r = l.indexOf(o.fieldName), n = l.indexOf(a.fieldName);
      return r === -1 && n !== -1 ? 1 : r !== -1 && n === -1 ? -1 : r === -1 && n === -1 ? 0 : r - n;
    }), s = t.filter((o) => o.type === "attachment" || o.type === "relationship");
    this.tableRef.setColumnOrder([...p, ...s]), this._updateTable(this.table.tableTemplate);
  }
  _getSortOrder(e) {
    const t = [...this.layer.fields];
    return e === "display" ? t.sort((l, i) => l.alias.localeCompare(i.alias)) : e === "field" ? t.sort((l, i) => l.name.localeCompare(i.name)) : e === "type" && t.sort((l, i) => l.type.localeCompare(i.type)), t.map((l) => l.name);
  }
  _getDifference(e, t) {
    return e.filter((l) => !t.includes(l));
  }
  _updateTable(e) {
    this.table.tableTemplate = e, this._isStandardView() && this._syncAttributeTableTemplate();
  }
  async _syncAttributeTableTemplate() {
    const e = this.table.layer;
    if (e.attributeTableTemplate) {
      const { _modules: t } = this, l = e.attributeTableTemplate.clone();
      t?.attributeTableTemplateUtils.syncAttributeTableTemplate(this.table, l), JSON.stringify(l) !== JSON.stringify(e.attributeTableTemplate) && (e.attributeTableTemplate = l);
    }
    if (e.attributeTableTemplate?.orderByFields?.length > 1) {
      const t = e.attributeTableTemplate.clone(), l = this.table.activeSortOrders[0];
      t.orderByFields = [
        { field: l.fieldName, order: l.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 l = document.createElement("calcite-tooltip");
    l.className = "table-tooltip", l.referenceElement = e, l.placement = "trailing-start", l.open = !0;
    const i = document.createElement("div");
    i.className = "tooltip", i.innerHTML = t, l.append(i), document.body.append(l);
  }
  _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: l } } } = e;
    return t && l;
  }
}
f("field-selection", C);
export {
  C as FieldSelection
};
