/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as _ } from "../../chunks/runtime.js";
import { css as M, html as S } from "lit";
import { keyed as P } from "lit/directives/keyed.js";
import { LitElement as W, createEvent as F } from "@arcgis/lumina";
import { Task as H } from "@lit/task";
import { createRef as G, ref as T } from "lit/directives/ref.js";
import { log as w, composeMissingPropertyMessage as N } from "@arcgis/toolkit/log";
import { formatDate as D, convertDateFormatToIntlOptions as b, formatDateOnly as J, formatTimeOnly as K, formatTimestamp as x, formatNumber as Q } from "@arcgis/core/intl.js";
import X from "@arcgis/core/smartMapping/statistics/uniqueValues.js";
import { clone as I } from "@arcgis/core/core/lang.js";
import { g as Z, i as h } from "../../chunks/commonFunctions.js";
import { u as Y } from "../../chunks/useT9n.js";
function U(i) {
  return (/* @__PURE__ */ new Date(`1970-01-01T${i}Z`)).getTime();
}
function L(i) {
  return (/* @__PURE__ */ new Date(`${i} 00:00:00`)).getTime();
}
function ee(i, e, s) {
  let t;
  return e === "unknown" ? t = D(i, {
    ...b("short-date-short-time"),
    timeZone: "utc",
    timeZoneName: "shortOffset"
  }) : t = D(i, {
    ...b("short-date-short-time"),
    timeZone: e
  }), t;
}
function te(i) {
  return i ? J(i, b("short-date")) : "";
}
function ie(i) {
  let e;
  return typeof i == "string" ? e = K(i, b("short-date-long-time")) : e = D(i, {
    ...b("long-time"),
    timeZone: "utc"
  }), e;
}
function se(i, e) {
  return typeof i == "string" ? e && "timeZone" in e && e.timeZone === "unknown" ? x(i, {
    ...b("short-date-short-time"),
    timeZone: "utc",
    timeZoneName: "shortOffset"
  }) : x(i, {
    ...b("short-date-short-time"),
    timeZone: e && "timeZone" in e && e.timeZone ? e.timeZone : "system"
  }) : e && "timeZone" in e && e.timeZone === "unknown" ? D(i, {
    ...b("short-date-short-time"),
    timeZone: "utc",
    timeZoneName: "shortOffset"
  }) : D(i, {
    ...b("short-date-short-time"),
    timeZone: e && "timeZone" in e && e.timeZone ? e.timeZone : "system"
  });
}
function z(i, e, s) {
  if (i.type !== "feature" && i.type !== "subtype-group" && i.type !== "subtype-sublayer" && i.type !== "imagery")
    return;
  let t;
  return Z(i, s).fields.forEach((p) => {
    const a = p.name, r = "domain" in p ? p.domain : void 0;
    if (i.type !== "imagery" && i.subtypeField === a) {
      let c;
      i.type === "subtype-group" || i.type === "feature" ? c = i.subtypes : c = i.parent.subtypes, c.forEach((l) => {
        i.type === "subtype-sublayer" && i.subtypeCode !== l.code || (e.name === a && (t = t || [], t.push({ code: l.code, name: l.name })), l.domains && Object.keys(l.domains).forEach((d) => {
          if (e.name === d) {
            const o = l.domains[d];
            o?.type === "coded-value" && o?.codedValues && o.codedValues.forEach((n) => {
              let g = !1;
              t = t || [], t.forEach((v) => {
                v.code === n.code && (g = !0, `| ${v.name} |`.includes(`| ${n.name} |`) || (v.name += ` | ${n.name}`));
              }), g || t.push({ code: n.code, name: n.name });
            });
          }
        }));
      });
    }
    if (e.name === a && (i.type === "feature" || i.type === "imagery")) {
      const c = i.type === "feature" ? i.typeIdField : void 0, l = i.type === "feature" ? i.types : void 0;
      i.type === "feature" && c && l ? (c === a ? t = l.map(
        (d) => (
          // fake coded Values
          {
            code: d.id,
            name: d.name
          }
        )
      ) : (t = t || [], l.forEach((d) => {
        if (!d.domains?.[a] || d.domains[a].type === "inherited") {
          const o = r;
          o?.codedValues && o.codedValues.forEach((n) => {
            let g = !1;
            t.forEach((v) => {
              v.code === n.code && (g = !0, `| ${v.name} |`.includes(`| ${n.name} |`) || (v.name += ` | ${n.name}`));
            }), g || t.push(I(n));
          });
        } else d.domains?.[a]?.codedValues && d.domains[a].codedValues.forEach((o) => {
          let n = !1;
          t.forEach((g) => {
            g.code === o.code && (n = !0, `| ${g.name} |`.includes(`| ${o.name} |`) || (g.name += ` | ${o.name}`));
          }), n || t.push(I(o));
        });
      })), !t?.length && r?.codedValues && (t = I(r.codedValues))) : r?.codedValues && (t = r.codedValues);
    }
  }), t;
}
function O(i, e) {
  const s = e;
  if (s) {
    let t = "";
    for (let u = 0; u < s.length; u++) {
      const p = s[u];
      p.code == i && (t += (t.length ? " | " : "") + p.name);
    }
    return t.length || (t = `${i}`), t;
  }
  return i;
}
function B(i) {
  return ["small-integer", "big-integer", "integer", "single", "double", "long"].includes(i.type);
}
function R(i) {
  switch (i.type) {
    case "small-integer":
    case "big-integer":
    case "integer":
    case "single":
    case "double":
    case "long":
      return "number";
    case "blob":
    case "geometry":
    case "global-id":
    case "guid":
    case "oid":
    case "raster":
    case "xml":
      return;
    default:
      return i.type;
  }
}
const ne = M`:host{width:100%}.container{min-height:30px}.popover-unique-list{width:100%;overflow-y:auto}.unique-values-content-list-msg{font-size:75%;margin:5px}.count{padding:0 6px;font-size:smaller;white-space:nowrap}`;
class oe extends W {
  constructor() {
    super(...arguments), this.dropdownNode = G(), this._messages = Y({ blocking: !0 }), this._propWatcherTask = new H(this, {
      task: async ([e, s, t]) => {
        const u = h(e) && h(s) || h(t);
        if (!h(t) && !h(e) && !h(s) ? w("error", this, N("uniqueValues")) : h(t) || (h(e) || w("error", this, N("layer")), h(s) || w("error", this, N("fieldName"))), h(e) && h(s)) {
          const { visualizationSource: p } = this;
          if (!Z(e, p).fields?.filter((c) => c.name === s))
            throw w("error", this, "Field could not be found."), new Error();
        }
        if (!u)
          throw new Error();
        await this.processProps();
      },
      args: () => [this.layer, this.fieldName, this.uniqueValues]
    }), this.initialRender = !0, this.multiple = !1, this.partialUniqueValues = !1, this.showFilterLength = 10, this.arcgisChange = F(), this.arcgisSortByChange = F(), this.arcgisLoad = F();
  }
  static {
    this.properties = { initialRender: 16, view: 0, layer: 0, visualizationSource: 1, fieldName: 1, uniqueValues: 0, numberFormatOptions: 0, selectedValues: 0, sortBy: 1, multiple: 5, partialUniqueValues: 5, showFilterLength: 9, maxHeight: 9 };
  }
  static {
    this.styles = ne;
  }
  async setFocus() {
    this.listNode?.setFocus();
  }
  async getUniqueValues() {
    const { fieldInfo: e } = this;
    if (h(e?.uniqueValueInfos)) {
      const { uniqueValueInfos: s, partialUniqueValues: t } = e;
      return { uniqueValues: s, partialUniqueValues: t };
    }
  }
  loaded() {
    this.layer && this.fieldInfo && (setTimeout(() => this.initialRender = !1, 800), this.listNode?.setFocus());
  }
  async processProps() {
    const { layer: e, fieldName: s, view: t, visualizationSource: u } = this, a = (e ? Z(e, u) : void 0)?.fields?.filter((r) => r.name === s)?.[0];
    if (h(this.uniqueValues))
      this.fieldInfo = {
        layerField: a,
        fieldDomains: e && a ? z(e, a, u) : void 0,
        simpleType: e && a ? R(a) : void 0,
        partialUniqueValues: this.partialUniqueValues ?? !1,
        uniqueValueInfos: this.uniqueValues
      }, this.arcgisLoad.emit();
    else if (e && a) {
      this.fieldInfo = {
        layerField: a,
        fieldDomains: z(e, a, u),
        simpleType: R(a),
        partialUniqueValues: !1
      };
      const { fieldInfo: r } = this;
      try {
        const c = await X({
          layer: e,
          view: t,
          field: s,
          sqlWhere: "definitionExpression" in e ? e.definitionExpression ?? void 0 : void 0,
          forBinning: !1
        }), l = B(a), d = c.uniqueValueInfos.filter((o) => h(o.value) ? a.type === "string" && !l || a.type === "guid" ? o.value !== "<Null>" && `${o.value}`.trim() !== "" : (B(a) || a.type === "oid" || l, o.value !== "<Null>" && o.value !== "") : !1);
        d.sort((o, n) => o.count > n.count ? -1 : o.count < n.count ? 1 : 0), r.fieldDomains?.length && r.fieldDomains.forEach((o) => {
          d.find((n) => n.value === o.code) || d.push({
            value: o.code,
            count: 0
          });
        }), r.uniqueValueInfos = d, r.partialUniqueValues = c.uniqueValueInfos.length === 2e3, this.arcgisLoad.emit();
      } catch (c) {
        if (w("error", this, `uniqueValues() - ${c.message}`), this.hasFieldDomains(r)) {
          const d = [];
          r.fieldDomains.forEach((o) => {
            d.find((n) => n.value === o.code) || d.push({
              value: o.code,
              count: void 0
            });
          });
        }
      }
      setTimeout(() => {
        this.initialRender = !1, this.listNode?.setFocus();
      }, 800);
    }
  }
  setListRef(e) {
    const { maxHeight: s } = this;
    this.listNode = e, s && e?.setAttribute("style", `max-height: ${s || 400}px`);
  }
  onSortMenuSelect(e) {
    const t = e.currentTarget.selectedItems?.[0].getAttribute("data-value");
    this.sortBy = t || void 0, this.arcgisSortByChange.emit(t || void 0);
  }
  isSameLists(e, s) {
    if (!e && !s)
      return !0;
    if (!e || !s || e?.length !== s?.length)
      return !1;
    for (let t = 0; t < e.length; t++)
      if (e[t] !== s[t])
        return !1;
    return !0;
  }
  hasFieldDomains(e) {
    return !!e.fieldDomains?.length;
  }
  render() {
    return this._propWatcherTask.render({
      complete: () => {
        const { fieldInfo: e, selectedValues: s, sortBy: t, multiple: u, initialRender: p, showFilterLength: a, _messages: r } = this, { fieldDomains: c, uniqueValueInfos: l, partialUniqueValues: d, layerField: o } = e, n = o?.type;
        if (!l?.length)
          return "";
        const g = n ? ["small-integer", "big-integer", "integer", "single", "double", "long", "oid"].includes(n) : !1, v = n ? ["date", "date-only", "time-only"].includes(n) : !1, k = (y) => {
          y.sort(($, m) => $.count <= m.count ? 1 : -1);
        }, A = (y) => {
          const $ = c?.length;
          y.sort((m, f) => {
            if (!$ && g)
              return (typeof m.value == "string" ? Number.parseFloat(m.value) : m.value) - (typeof f.value == "string" ? Number.parseFloat(f.value) : f.value);
            {
              const q = $ ? O(m.value, c) : m.value, V = $ ? O(f.value, c) : f.value;
              return `${q}`.startsWith("_") ? 1 : `${V}`.startsWith("_") ? -1 : `${q}`.localeCompare(`${V}`);
            }
          });
        }, C = (y, $) => {
          y.sort((m, f) => {
            const q = $?.indexOf(m.value) ?? -1, V = $?.indexOf(f.value) ?? -1;
            return q === V || q > -1 && V > -1 ? 0 : q > V ? -1 : 1;
          });
        };
        A(l), !t || t === "count" ? k(l) : t === "selected" && C(l, s);
        const j = l.map((y) => this.renderUniqueValue(y));
        let E;
        return d && !p && (E = S`<div class="unique-values-content-list-msg">${r.errors.tooManyUniqueValues}</div>`), S`<div class="container"><calcite-list .label=${r.values} class="popover-unique-list" .filterEnabled=${l.length >= a} .selectionMode=${u ? "multiple" : "single"} .filterPlaceholder=${r.searchValues} @calciteListChange=${(y) => {
          let m = y.target.selectedItems.map((f) => f.value);
          !c && n === "date-only" ? m = m?.map((f) => L(f)) : !c && n === "time-only" ? m = m?.map((f) => U(f)) : n && ["date", "oid", "small-integer", "big-integer", "integer", "long"].includes(n) ? m = m?.map((f) => Number.parseInt(f)) : n && ["single", "double"].includes(n) && (m = m?.map((f) => Number.parseFloat(f))), !this.isSameLists(m, this.selectedValues) && (this.selectedValues = m, this.arcgisChange.emit(m));
        }} @calciteListFilter=${() => {
          this.dropdownNode.value && (this.dropdownNode.value.disabled = this.listNode.filteredItems.length < 4);
        }} ${T(this.setListRef)}>${l.length >= a && !p ? this.renderSort(g, v) : null}${j}</calcite-list>${E}</div>`;
      },
      error: () => ""
    });
  }
  renderSort(e, s) {
    const { sortBy: t, _messages: u } = this;
    return S`<calcite-dropdown slot=filter-actions-end placement=bottom-end overlay-positioning=fixed @calciteDropdownSelect=${this.onSortMenuSelect} ${T(this.dropdownNode)}><calcite-action slot=trigger .label=${u.sortValues} text><calcite-icon scale=s icon=sortDescending flip-rtl></calcite-icon></calcite-action><calcite-dropdown-group><calcite-dropdown-item .selected=${t === "count" || !h(t)} data-value=count>${u.sortByCount}</calcite-dropdown-item><calcite-dropdown-item .selected=${t === "name"} data-value=name>${e || s ? u.sortAscending : u.sortAlphabetical}</calcite-dropdown-item><calcite-dropdown-item .selected=${t === "selected"} data-value=selected>${u.sortSelected}</calcite-dropdown-item></calcite-dropdown-group></calcite-dropdown>`;
  }
  renderUniqueValue(e) {
    const { selectedValues: s, initialRender: t, view: u, fieldInfo: p, numberFormatOptions: a } = this, { fieldDomains: r, uniqueValueInfos: c, simpleType: l } = p, d = u && "timeZone" in u && u.timeZone || "system", o = r?.length ? O(e.value, r) : l === "date" ? ee(e.value, d) : l === "date-only" ? te(e.value) : l === "time-only" ? ie(e.value) : l === "timestamp-offset" ? se(e.value, u) : typeof e.value == "number" ? Q(e.value, a) : e.value, n = s ? l === "date-only" ? s.includes(r?.length ? e.value : L(e.value)) : l === "time-only" ? s.includes(r?.length ? e.value : U(e.value)) : s.includes(e.value) : !1;
    return P(`list-item_${e.value}`, S`<calcite-list-item .label=${`${o}`} .value=${`${e.value}`} .selected=${n}>${h(e.count) && (c.length > 200 && !t || c.length <= 200) ? S`<div class="count" slot=actions-end>${`${e.count}`}</div>` : null}</calcite-list-item>`);
  }
}
_("arcgis-unique-values-list", oe);
export {
  oe as ArcgisUniqueValuesList
};
