import { c as M } from "../../chunks/runtime.js";
import { css as P, html as V } from "lit";
import { keyed as W } from "lit/directives/keyed.js";
import { LitElement as z, createEvent as F } 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 q, composeMissingPropertyMessage as D } 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 m } 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.123 */
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 s = o.name, r = o.domain;
    if (i.type !== "imagery" && i.subtypeField === s) {
      let f;
      i.type === "subtype-group" || i.type === "feature" ? f = i.subtypes : f = i.parent.subtypes, f.forEach((a) => {
        i.type === "subtype-sublayer" && i.subtypeCode !== a.code || (e.name === s && (t = t || [], t.push({ code: a.code, name: a.name })), a.domains && Object.keys(a.domains).forEach((l) => {
          if (e.name === l) {
            const n = a.domains[l];
            n?.type === "coded-value" && n?.codedValues && n.codedValues.forEach((u) => {
              let p = !1;
              t = t || [], t.forEach((d) => {
                d.code === u.code && (p = !0, `| ${d.name} |`.includes(`| ${u.name} |`) || (d.name += ` | ${u.name}`));
              }), p || t.push({ code: u.code, name: u.name });
            });
          }
        }));
      });
    }
    if (e.name === s && (i.type === "feature" || i.type === "imagery")) {
      const f = i.type === "feature" ? i.typeIdField : void 0, a = i.type === "feature" ? i.types : void 0;
      i.type === "feature" && f && a ? (f === s ? t = a.map(
        (l) => (
          // fake coded Values
          {
            code: l.id,
            name: l.name
          }
        )
      ) : (t = t || [], a.forEach((l) => {
        if (!l.domains?.[s] || l.domains[s].type === "inherited") {
          const n = r;
          n?.codedValues && n.codedValues.forEach((u) => {
            let p = !1;
            t.forEach((d) => {
              d.code === u.code && (p = !0, `| ${d.name} |`.includes(`| ${u.name} |`) || (d.name += ` | ${u.name}`));
            }), p || t.push(N(u));
          });
        } else l.domains?.[s]?.codedValues && l.domains[s].codedValues.forEach((n) => {
          let u = !1;
          t.forEach((p) => {
            p.code === n.code && (u = !0, `| ${p.name} |`.includes(`| ${n.name} |`) || (p.name += ` | ${n.name}`));
          }), u || t.push(N(n));
        });
      })), !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 s = 0; s < t.length; s++) {
      const r = t[s];
      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, s]) => {
        const r = m(t) && m(o) && m(e) || m(s);
        if (!m(s) && !m(t) && !m(o) && !m(e) ? q("error", this, D("uniqueValues")) : m(s) || (m(t) || q("error", this, D("layer")), m(o) || q("error", this, D("fieldName")), m(e) || q("error", this, D("view"))), m(t) && m(o) && !t.fields?.filter((a) => a.name === o))
          throw q("error", this, "Field could not be found."), new Error();
        if (!r)
          throw new Error();
        await this.processProps();
      },
      args: () => [this.view, 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, 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 (m(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, s = e?.fields?.filter((r) => r.name === t)?.[0];
    if (m(this.uniqueValues))
      this.fieldInfo = {
        layerField: s,
        fieldDomains: e && s ? U(e, s) : void 0,
        simpleType: e && s ? B(s) : void 0,
        partialUniqueValues: this.partialUniqueValues ?? !1,
        uniqueValueInfos: this.uniqueValues
      }, this.arcgisLoad.emit();
    else if (e && s) {
      this.fieldInfo = {
        layerField: s,
        fieldDomains: U(e, s),
        simpleType: B(s),
        partialUniqueValues: !1
      };
      const { fieldInfo: r } = this;
      try {
        const f = await Q({
          layer: e,
          view: o,
          field: t,
          sqlWhere: "definitionExpression" in e ? e.definitionExpression ?? void 0 : void 0,
          forBinning: !1
        }), a = L(s), l = f.uniqueValueInfos.filter((n) => m(n.value) ? s.type === "string" && !a || s.type === "guid" ? n.value !== "<Null>" && `${n.value}`.trim() !== "" : (L(s) || s.type === "oid" || a, n.value !== "<Null>" && n.value !== "") : !1);
        l.sort((n, u) => n.count > u.count ? -1 : n.count < u.count ? 1 : 0), r.fieldDomains?.length && r.fieldDomains.forEach((n) => {
          l.find((u) => u.value === n.code) || l.push({
            value: n.code,
            count: 0
          });
        }), r.uniqueValueInfos = l, r.partialUniqueValues = f.uniqueValueInfos.length === 2e3, this.arcgisLoad.emit();
      } catch (f) {
        if (q("error", this, `uniqueValues() - ${f.message}`), this.hasFieldDomains(r)) {
          const l = [];
          r.fieldDomains.forEach((n) => {
            l.find((u) => u.value === n.code) || l.push({
              value: n.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: s, initialRender: r, showFilterLength: f, _messages: a } = this, { fieldDomains: l, uniqueValueInfos: n, partialUniqueValues: u, layerField: p } = e, d = p?.type;
        if (!n?.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, h) => {
            if (!y && Z)
              return (typeof c.value == "string" ? Number.parseFloat(c.value) : c.value) - (typeof h.value == "string" ? Number.parseFloat(h.value) : h.value);
            {
              const $ = y ? I(c.value, l) : c.value, b = y ? I(h.value, l) : h.value;
              return `${$}`.startsWith("_") ? 1 : `${b}`.startsWith("_") ? -1 : `${$}`.localeCompare(`${b}`);
            }
          });
        }, C = (g, y) => {
          g.sort((c, h) => {
            const $ = y?.indexOf(c.value) ?? -1, b = y?.indexOf(h.value) ?? -1;
            return $ === b || $ > -1 && b > -1 ? 0 : $ > b ? -1 : 1;
          });
        };
        A(n), !o || o === "count" ? k(n) : o === "selected" && C(n, t);
        const _ = n.map((g) => this.renderUniqueValue(g));
        let E;
        return u && !r && (E = V`<div class="unique-values-content-list-msg">${a.errors.tooManyUniqueValues}</div>`), V`<div class="container"><calcite-list .label=${a.values} class="popover-unique-list" .filterEnabled=${n.length >= f} .selectionMode=${s ? "multiple" : "single"} .filterPlaceholder=${a.searchValues} @calciteListChange=${(g) => {
          let c = g.target.selectedItems.map((h) => h.value);
          !l && d === "date-only" ? c = c?.map((h) => O(h)) : !l && d === "time-only" ? c = c?.map((h) => x(h)) : d && ["date", "oid", "small-integer", "big-integer", "integer", "long"].includes(d) ? c = c?.map((h) => Number.parseInt(h)) : d && ["single", "double"].includes(d) && (c = c?.map((h) => Number.parseFloat(h))), !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)}>${n.length >= f && !r ? this.renderSort(Z, R) : null}${_}</calcite-list>${E}</div>`;
      },
      error: () => ""
    });
  }
  renderSort(e, t) {
    const { sortBy: o, _messages: s } = this;
    return V`<calcite-dropdown slot=filter-actions-end placement=bottom-end overlay-positioning=fixed @calciteDropdownSelect=${this.onSortMenuSelect} ${S(this.dropdownNode)}><calcite-action slot=trigger .label=${s.sortValues} text><calcite-icon scale=s icon=sortDescending flip-rtl></calcite-icon></calcite-action><calcite-dropdown-group><calcite-dropdown-item .selected=${o === "count" || !m(o)} data-value=count>${s.sortByCount}</calcite-dropdown-item><calcite-dropdown-item .selected=${o === "name"} data-value=name>${e || t ? s.sortAscending : s.sortAlphabetical}</calcite-dropdown-item><calcite-dropdown-item .selected=${o === "selected"} data-value=selected>${s.sortSelected}</calcite-dropdown-item></calcite-dropdown-group></calcite-dropdown>`;
  }
  renderUniqueValue(e) {
    const { selectedValues: t, initialRender: o, view: s, fieldInfo: r, numberFormatOptions: f } = this, { fieldDomains: a, uniqueValueInfos: l, simpleType: n } = r, u = s && "timeZone" in s && s.timeZone || "system", p = a?.length ? I(e.value, a) : n === "date" ? Y(e.value, u) : n === "date-only" ? ee(e.value) : n === "time-only" ? te(e.value) : n === "timestamp-offset" ? ie(e.value, s) : typeof e.value == "number" ? K(e.value, f) : e.value, d = t ? n === "date-only" ? t.includes(a?.length ? e.value : O(e.value)) : n === "time-only" ? t.includes(a?.length ? e.value : x(e.value)) : t.includes(e.value) : !1;
    return W(`list-item_${e.value}`, V`<calcite-list-item .label=${`${p}`} .value=${`${e.value}`} .selected=${d}>${m(e.count) && (l.length > 200 && !o || l.length <= 200) ? V`<div class="count" slot=actions-end>${`${e.count}`}</div>` : null}</calcite-list-item>`);
  }
}
M("arcgis-unique-values-list", ne);
export {
  ne as ArcgisUniqueValuesList
};
