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