import { c as A } from "../../chunks/runtime.js";
import { css as q, html as p } from "lit";
import { keyed as F } from "lit/directives/keyed.js";
import { ref as E } from "lit/directives/ref.js";
import { LitElement as L, createEvent as N, safeClassMap as T } from "@arcgis/lumina";
import { Task as R } from "@lit/task";
import { log as D, composeMissingPropertyMessage as b } from "@arcgis/toolkit/log";
import M from "@arcgis/core/config.js";
import * as _ from "@arcgis/core/core/reactiveUtils.js";
import * as y from "@arcgis/core/intl.js";
import * as I from "@arcgis/core/core/lang.js";
import x from "@arcgis/core/smartMapping/statistics/summaryStatistics.js";
import G from "@arcgis/core/smartMapping/statistics/uniqueValues.js";
import { s as C } from "../../chunks/commonFunctions.js";
import U from "@arcgis/core/rest/support/Query.js";
import { u as P } 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 */
var l = /* @__PURE__ */ ((s) => (s.MISSING = "missing", s.IN_PROGRESS = "inProgress", s.SUCCESS = "success", s.FAILED = "failed", s))(l || {}), u = /* @__PURE__ */ ((s) => (s.DATE = "date", s.DATE_ONLY = "date-only", s.GUID = "guid", s.NUMBER = "number", s.OID = "oid", s.STRING = "string", s.TIME_ONLY = "time-only", s.TIMESTAMP_OFFSET = "timestamp-offset", s.UNKNOWN = "unknown", s))(u || {});
function g(s) {
  return s != null;
}
function k(s) {
  return s.type === "scene" ? s.associatedLayer?.url : s.url;
}
const Z = {
  dateStyle: "short",
  timeStyle: "short"
}, Y = {
  timeStyle: "medium"
};
function W(s) {
  const { layer: e, fieldName: t } = s;
  let i;
  const n = C(e);
  let a;
  "popupTemplate" in e && (a = e.popupTemplate);
  const r = a ? a.fieldInfos : [];
  return V(s)?.filter((d) => d.name === t).forEach((d) => {
    const c = !n && r ? r.filter((v) => v.fieldName === d.name) : null, o = n ? e.getFieldAlias(t) : c?.length ? c[0].label : d.alias;
    /^raster.(item|service)pixelvalue/iu.test(t) && (d.type = "double");
    const m = {
      layerField: d,
      label: o || d.name
    };
    m.codedValues = j(t, s), H(m), m.simpleFieldType && (i = m);
  }), i;
}
function V(s) {
  const { layer: e } = s;
  return e.type === "imagery-tile" || e.type === "wcs" || e.type === "imagery" && e.rasterFields.length ? e.rasterFields : e.fields;
}
async function O(s) {
  s.statisticsStatus = l.IN_PROGRESS;
  const { layer: e, view: t } = s;
  if (e.type === "imagery-tile" || e.type === "wcs" || e.type === "stream" || e.type === "voxel")
    throw new Error("could not get feature count");
  try {
    return await K(e, t);
  } catch {
    return;
  }
}
async function Q(s) {
  const { layer: e, view: t, fieldName: i, fieldInfo: n } = s;
  if (e.type === "imagery-tile" || e.type === "wcs" || e.type === "voxel")
    throw new Error("could not get statistics for ImageryTileLayer/WCSLayer/VoxelLayer");
  if (!n || n.layerField.type === "oid" || n.layerField.type === "guid" || n.layerField.type === "global-id")
    return { totalCount: await O(s), nullcount: 0 };
  try {
    const a = await x({
      layer: e,
      view: t,
      field: i,
      outStatisticTypes: { exclude: ["median"] }
    });
    if (!g(a.count))
      throw new Error("could not get statistics");
    const r = "sourceJSON" in e && e.sourceJSON.maxRecordCount === a.count;
    if (g(a.nullcount) && !r)
      return { ...a, totalCount: a.count + a.nullcount };
    {
      const f = await O(s);
      return { ...a, totalCount: f };
    }
  } catch {
    throw new Error("could not get statistics");
  }
}
async function B(s) {
  const { layer: e, view: t, fieldName: i } = s;
  if (e.type === "imagery-tile" || e.type === "wcs" || e.type === "voxel")
    throw new Error("could not get unique values for ImageryLayer/ImageryTileLayer/WCSLayer/VoxelLayer");
  e.type === "feature" && !e.url && (e.outFields = ["*"]);
  try {
    return await G({
      layer: e,
      view: t,
      field: i
    });
  } catch {
    throw new Error("could not get unique values");
  }
}
function H(s) {
  switch (s.layerField.type) {
    case "string":
      s.simpleFieldType = u.STRING;
      break;
    case "date":
      s.simpleFieldType = u.DATE;
      break;
    case "timestamp-offset":
      s.simpleFieldType = u.TIMESTAMP_OFFSET;
      break;
    case "date-only":
      s.simpleFieldType = u.DATE_ONLY;
      break;
    case "time-only":
      s.simpleFieldType = u.TIME_ONLY;
      break;
    case "oid":
      s.simpleFieldType = u.OID;
      break;
    case "guid":
    case "global-id":
      s.simpleFieldType = u.GUID;
      break;
    case "small-integer":
    case "big-integer":
    case "integer":
    case "single":
    case "double":
    case "long":
      s.simpleFieldType = u.NUMBER;
      break;
  }
}
function j(s, e) {
  const { layer: t } = e;
  if (t.type === "subtype-sublayer" && t.subtypeField === s) {
    const c = t.parent?.subtypes?.find((o) => o.code === t.subtypeCode);
    if (c)
      return [{ code: c.code, name: c.name }];
  }
  if (t.type !== "feature" && t.type !== "imagery")
    return;
  const i = t.type === "feature" ? t.typeIdField : void 0, n = t.type === "feature" ? t.types : void 0;
  let a;
  const f = V(e)?.find((c) => c.name === s), d = f?.domain;
  return t.type === "feature" && i && n ? (i === s ? a = n.map(
    (c) => (
      // fake coded values
      {
        code: c.id,
        name: c.name
      }
    )
  ) : (a = [], n.forEach((c) => {
    if (!c.domains[s] || c.domains[s].type === "inherited") {
      const o = d;
      o?.codedValues && o.codedValues.forEach(async (m) => {
        let v = !1;
        a.forEach((h) => {
          h.code === m.code && (v = !0, `, ${h.name},`.includes(`, ${m.name},`) || (h.name += `, ${m.name}`));
        }), v || a.push(I.clone(m));
      });
    } else c.domains[s].codedValues && c.domains[s].codedValues.forEach(async (o) => {
      let m = !1;
      a.forEach((v) => {
        v.code === o.code && (m = !0, `, ${v.name},`.includes(`, ${o.name},`) || (v.name += `, ${o.name}`));
      }), m || a.push(I.clone(o));
    });
  })), !a.length && d?.codedValues && (a = I.clone(d.codedValues))) : d?.codedValues && (a = f.domain.codedValues), a?.length ? a : null;
}
async function J(s) {
  const { view: e, layer: t } = s;
  if (t.type === "imagery" || t.type === "imagery-tile" || t.type === "wcs")
    throw new Error("could not get feature");
  if (t.type === "feature" && !t.url || t.type === "wfs") {
    const i = t.createQuery();
    i.start = 0, i.num = 5, i.outFields = ["*"];
    const n = await t.queryFeatures(i);
    if (n.features.length)
      return n;
    throw new Error("could not get feature");
  } else {
    if (!e)
      return await w(s);
    let i;
    if (t.type === "subtype-sublayer" || t.type === "sublayer") {
      let a = t.parent;
      for (; ["subtype-group", "map-image"].includes(a.type); )
        a = a.parent;
      i = await e.whenLayerView(a);
    } else
      i = await e.whenLayerView(t);
    if (i.availableFields.length === t.fields.length || ["stream", "ogc-feature"].includes(t.type) && i.availableFields.length > 0) {
      const a = t.createQuery();
      a.start = 0, a.num = 5, a.outFields = ["*"];
      const r = await i.queryFeatures(a);
      return r.features?.length ? r : await w(s);
    } else
      return await w(s);
  }
}
async function w(s) {
  const { layer: e } = s;
  if (["imagery", "imagery-tile", "stream", "ogc-feature"].includes(e.type))
    throw new Error("cannot get feature from service");
  const t = new U({
    where: "1=1",
    outFields: ["*"],
    returnGeometry: !1
  });
  return "sourceJSON" in e && e.sourceJSON?.advancedQueryCapabilities?.supportsPagination && (t.num = 1), await e.queryFeatures(t);
}
async function K(s, e) {
  if (s.type === "feature" && !s.url)
    return await z(s);
  if (s.type === "feature" || s.type === "csv" || s.type === "scene" || s.type === "wfs" || s.type === "geojson")
    return await s.queryFeatureCount();
  if (e && (s.type === "stream" || s.type === "ogc-feature"))
    return await X(s, e);
}
async function z(s) {
  const e = s.createQuery();
  e.outFields = ["*"];
  const t = await s.queryFeatures(e);
  if (t.features.length)
    return t.features.length;
  throw new Error("could not get feature count");
}
async function X(s, e) {
  return await (await e.whenLayerView(s)).queryFeatureCount();
}
const ee = q`:host{height:100%}.container{padding:var(--calcite-space-xs);background-color:var(--calcite-color-foreground-1)}.title{font-weight:700;padding:5px 0}.missing,.data{color:#a9a9a9}.count{white-space:nowrap}.section{padding:var(--calcite-space-xs) 0}.statistics-row{border-top:var(--calcite-border-width-sm) solid var(--calcite-color-border-2);padding:var(--calcite-space-xs) 0;display:flex;justify-content:space-between}.statistics-row-top-values{border-top:var(--calcite-border-width-sm) solid var(--calctie-color-border-2);padding:20px 0 var(--calcite-space-xs) 0;display:flex;justify-content:space-between}`;
class te extends L {
  constructor() {
    super(...arguments), this._messages = P({ blocking: !0 }), this._propWatcherTask = new R(this, {
      task: async ([e, t]) => {
        const i = g(e) && g(t);
        if (g(e) || D("error", this, b("layer")), g(t) || D("error", this, b("fieldName")), !i)
          throw new Error();
        await this.processProps(), this._propWatcherTask.autoRun = !1;
      },
      args: () => [this.layer, this.fieldName]
    }), this.oneFeatureResponseStatus = l.MISSING, this.statisticsStatus = l.MISSING, this.uniqueValuesStatus = l.MISSING, this.hideAlias = !1, this.hideNumericFormat = !1, this.hideStatistics = !1, this.arcgisComplete = N(), this.arcgisFieldInfoComplete = N();
  }
  static {
    this.properties = { oneFeatureResponseStatus: 16, oneFeatureResponse: 16, statisticsStatus: 16, statistics: 16, uniqueValuesStatus: 16, uniqueValues: 16, view: 0, layer: 0, fieldName: 1, hideAlias: 5, hideNumericFormat: 5, hideStatistics: 5 };
  }
  static {
    this.styles = ee;
  }
  async refresh() {
    await this.processProps(), this.requestUpdate();
  }
  disconnectedCallback() {
    super.disconnectedCallback(), this.timeZoneHandle?.remove();
  }
  async processProps() {
    const { view: e, layer: t, fieldName: i, hideStatistics: n } = this;
    if (!t || !i)
      return;
    let a;
    if (t.declaredClass === "esri.layers.support.Sublayer") {
      const r = t;
      e && await _.whenOnce(() => !e.updating), a = await r.createFeatureLayer(), await a?.load();
    }
    this.props = {
      view: e,
      layer: a ?? t,
      fieldName: i,
      hideStatistics: n
    }, this.props.fieldInfo = W(this.props), t.type === "scene" && M.request.interceptors?.push({
      urls: `${k(t)}/${t.layerId}`,
      before(r) {
        r.requestOptions.authMode = "no-prompt";
      }
    }), this.oneFeatureResponseStatus = l.IN_PROGRESS;
    try {
      const r = await J(this.props);
      this.oneFeatureResponse = r, this.oneFeatureResponseStatus = l.SUCCESS;
    } catch {
      this.oneFeatureResponseStatus = l.FAILED;
    }
    if (t.type === "stream") {
      this.uniqueValuesStatus = l.FAILED, this.statisticsStatus = l.FAILED;
      return;
    }
    if (n)
      this.uniqueValuesStatus = l.FAILED;
    else {
      this.uniqueValuesStatus = l.IN_PROGRESS;
      try {
        const r = await B(this.props);
        this.uniqueValues = r, r?.uniqueValueInfos?.length ? this.uniqueValuesStatus = l.SUCCESS : this.uniqueValuesStatus = l.FAILED;
      } catch {
        this.uniqueValuesStatus = l.FAILED;
      }
    }
    if (n)
      this.statisticsStatus = l.FAILED;
    else {
      this.statisticsStatus = l.IN_PROGRESS;
      try {
        const r = await Q(this.props);
        if (!g(r.totalCount) && g(r.count) && this.uniqueValuesStatus === l.SUCCESS) {
          const f = this.uniqueValues?.uniqueValueInfos ?? [];
          for (let d = 0; d < f.length; d++) {
            const c = f[d];
            if (c.value === null) {
              r.totalCount = c.count + r.count;
              break;
            }
          }
          r.totalCount ??= r.count;
        }
        this.statistics = r, this.statisticsStatus = l.SUCCESS;
      } catch {
        this.statisticsStatus = l.FAILED;
      }
    }
    this.setUpTimeZoneHandle();
  }
  setUpTimeZoneHandle() {
    this.timeZoneHandle?.remove();
    const { props: e } = this, { view: t, fieldInfo: i } = e;
    [u.DATE, u.TIMESTAMP_OFFSET].includes(this._getStatisticsType(i)) && (this.timeZoneHandle = _.watch(() => t?.timeZone, () => {
      this.requestUpdate();
    }));
  }
  _getFieldTypeLabel(e) {
    const { _messages: t } = this, i = t.fieldTypes;
    switch (e) {
      case "big-integer":
        return i.bigInteger;
      case "date":
        return i.date;
      case "date-only":
        return i.dateOnly;
      case "double":
        return i.double;
      case "global-id":
        return i.globalId;
      case "guid":
        return i.guid;
      case "integer":
        return i.integer;
      case "long":
        return i.long;
      case "oid":
        return i.oid;
      case "single":
        return i.single;
      case "small-integer":
        return i.smallInteger;
      case "string":
        return i.string;
      case "time-only":
        return i.timeOnly;
      case "timestamp-offset":
        return i.timestampOffset;
      default:
        return i.string;
    }
  }
  _getStatisticsType(e) {
    switch (e.layerField.type) {
      case "big-integer":
      case "double":
      case "integer":
      case "single":
      case "small-integer": {
        if (e.codedValues)
          return u.STRING;
        switch (e.layerField.valueType) {
          case "binary":
          case "description":
          case "location-or-place-name":
          case "name-or-title":
          case "ordered-or-ranked":
          case "type-or-category":
            return u.STRING;
          default:
            return u.NUMBER;
        }
      }
      case "date":
        return u.DATE;
      case "date-only":
        return u.DATE_ONLY;
      case "string":
        return u.STRING;
      case "time-only":
        return u.TIME_ONLY;
      case "timestamp-offset":
        return u.TIMESTAMP_OFFSET;
      default:
        return u.STRING;
    }
  }
  _getFieldValueTypeCamelCase(e) {
    switch (e.layerField.valueType) {
      case "count-or-amount":
        return "countOrAmount";
      case "date-and-time":
        return "dateAndTime";
      case "location-or-place-name":
        return "locationOrPlaceName";
      case "name-or-title":
        return "nameOrTitle";
      case "ordered-or-ranked":
        return "orderedOrRanked";
      case "percentage-or-ratio":
        return "percentageOrRatio";
      case "type-or-category":
        return "typeOrCategory";
      case "unique-identifier":
        return "uniqueIdentifier";
      case "phone-number":
        return "phoneNumber";
      case "email-address":
        return "emailAddress";
      default:
        return e.layerField.valueType;
    }
  }
  _getDisplayString(e, t) {
    const { props: i } = this, { fieldInfo: n } = i;
    switch (n.simpleFieldType) {
      case u.DATE:
        return this._getDateString(e, t);
      case u.DATE_ONLY:
        return this._getDateOnlyString(e, t);
      case u.GUID:
        return this._getGuidString(e);
      case u.NUMBER:
        return this._getNumberString(e, t);
      case u.TIME_ONLY:
        return this._getTimeOnlyString(e, t);
      case u.TIMESTAMP_OFFSET:
        return this._getTimestampOffsetString(e, t);
      default:
        return `${e}`;
    }
  }
  _getDateString(e, t) {
    const { view: i } = this.props;
    return i && i.timeZone === "unknown" ? y.formatDate(e, {
      ...this.getIntlDateTimeFormattingOptions("short-date-short-time", t),
      timeZone: "utc"
    }) : y.formatDate(e, {
      ...this.getIntlDateTimeFormattingOptions("short-date-short-time", t),
      timeZone: i?.timeZone || "system"
    });
  }
  _getTimestampOffsetString(e, t) {
    const { view: i } = this.props;
    return typeof e == "string" ? i && i.timeZone === "unknown" ? y.formatTimestamp(e, {
      ...this.getIntlDateTimeFormattingOptions("short-date-short-time", t),
      timeZone: "utc"
    }) : y.formatTimestamp(e, {
      ...this.getIntlDateTimeFormattingOptions("short-date-short-time", t),
      timeZone: i?.timeZone || "system"
    }) : this._getDateString(e, t);
  }
  _getDateOnlyString(e, t) {
    return y.formatDateOnly(e, this.getIntlDateTimeFormattingOptions("short-date", t));
  }
  _getTimeOnlyString(e, t) {
    return typeof e == "string" ? y.formatTimeOnly(e, this.getIntlDateTimeFormattingOptions("short-date-long-time", t)) : y.formatDate(e, {
      ...this.getIntlDateTimeFormattingOptions("long-time", {
        ...t,
        isTimeOnly: !0
      }),
      timeZone: "utc"
    });
  }
  _getGuidString(e) {
    return e.startsWith("{") ? e : `{${e}}`;
  }
  _getNumberString(e, t) {
    const i = t?.useFieldFormatting ? e : Math.round(e * 100) / 100;
    return y.formatNumber(i, this.getIntlNumberFormattingOptions(t));
  }
  _printNumValue(e, t) {
    return g(e) ? this._getNumberString(e, t) : "--";
  }
  _setCompleteRef() {
    this.arcgisComplete.emit(), this.arcgisFieldInfoComplete.emit();
  }
  getCurrentFieldFormat() {
    const { props: e } = this, { layer: t, fieldName: i } = e;
    return (this.originalLayerSupportsFieldConfiguration() ? t.getFieldConfiguration(i) : void 0)?.fieldFormat;
  }
  getIntlNumberFormattingOptions(e) {
    const t = this.getCurrentFieldFormat();
    if (!e?.useFieldFormatting)
      return t ? {
        useGrouping: ["always", "auto"].includes(t.useGrouping)
      } : y.convertNumberFormatToIntlOptions({
        digitSeparator: this.getPopupTemplateFieldInfo()?.format?.digitSeparator ?? !0
      });
    const i = t ? {
      minimumFractionDigits: t.minimumFractionDigits,
      maximumFractionDigits: t.maximumFractionDigits,
      useGrouping: ["always", "auto"].includes(t.useGrouping)
    } : void 0;
    if (i)
      return i;
    const n = this.getPopupTemplateFieldInfo();
    return y.convertNumberFormatToIntlOptions({
      digitSeparator: n?.format?.digitSeparator ?? !0,
      places: n?.format?.places ?? 2
    });
  }
  getIntlDateTimeFormattingOptions(e, t) {
    const i = this.getCurrentFieldFormat();
    if (!t?.useFieldFormatting)
      return i ? t?.isTimeOnly ? Y : Z : y.convertDateFormatToIntlOptions(e);
    const n = i ? {
      dateStyle: t?.isTimeOnly ? void 0 : i.dateStyle ?? void 0,
      // year/month is overridden if dateStyle is set
      year: i.dateStyle ? void 0 : i.year ?? void 0,
      month: i.dateStyle ? void 0 : i.month ?? void 0,
      timeStyle: i.timeStyle ?? void 0,
      hourCycle: i.hour12 === "never" ? "h23" : "h11"
    } : void 0;
    if (n)
      return n;
    const a = this.getPopupTemplateFieldInfo();
    return y.convertDateFormatToIntlOptions(a?.format?.dateFormat ?? e);
  }
  originalLayerSupportsFieldConfiguration() {
    const { layer: e } = this;
    return C(e);
  }
  getPopupTemplateFieldInfo() {
    const { props: e } = this, { layer: t, fieldName: i } = e;
    return ("popupTemplate" in t ? t.popupTemplate : void 0)?.fieldInfos?.find((a) => a.fieldName === i);
  }
  render() {
    return this._propWatcherTask.render({
      complete: () => {
        const { props: e } = this, { fieldInfo: t } = e;
        return t ? p`<div class="container">${this.renderFieldType()}${this.renderFieldAlias()}${this.renderFieldDescription()}${this.renderFieldValueType()}${this.renderFieldSampleValue()}${this.renderFieldNumericFormat()}${this.renderFieldStatistics()}</div>` : "";
      },
      error: () => ""
    });
  }
  renderFieldType() {
    const { _messages: e, props: t } = this, { fieldInfo: i } = t, n = this._getFieldTypeLabel(i.layerField.type);
    return p`<div class="section"><div class="title">${e.fieldType}</div><div>${n}</div></div>`;
  }
  renderFieldAlias() {
    const { _messages: e, props: t, hideAlias: i } = this, { fieldInfo: n } = t;
    return i ? "" : p`<div class="section"><div class="title">${e.fieldAlias}</div><div>${n.label}</div></div>`;
  }
  renderFieldDescription() {
    const { _messages: e, props: t } = this, { layer: i } = t;
    if (i.type !== "feature")
      return "";
    const { fieldInfo: n } = t, a = n.layerField.description;
    return p`<div class="section"><div class="title">${e.fieldDescription}</div><div class=${T({
      missing: !a
    })}>${a || e.fieldDescriptionNotSet}</div></div>`;
  }
  renderFieldValueType() {
    const { _messages: e, props: t } = this, { layer: i } = t;
    if (i.type !== "feature")
      return "";
    const { fieldInfo: n } = t, a = this._getFieldValueTypeCamelCase(n);
    return p`<div class="section"><div class="title">${e.fieldValueType}</div><div class=${T(a ? "" : "missing")}>${a ? e.fieldValueTypes[a] : e.fieldValueTypeNotSet}</div></div>`;
  }
  renderFieldSampleValue() {
    const { oneFeatureResponse: e, oneFeatureResponseStatus: t, statisticsStatus: i, statistics: n, uniqueValuesStatus: a, uniqueValues: r, _messages: f, props: d } = this, { layer: c, fieldName: o, fieldInfo: m } = d, { statistics: v } = f;
    let h;
    if (["imagery-tile", "voxel"].includes(c.type) || c.type !== "stream" && [u.STRING, u.OID, u.GUID].includes(this._getStatisticsType(m)) && a !== l.FAILED)
      return "";
    t === l.SUCCESS ? e.features.forEach((S) => {
      (h === void 0 || h === null && S.attributes[o] !== null) && (h = S.attributes[o]);
    }) : i === l.SUCCESS ? h = n?.min : a === l.SUCCESS && (h = r?.uniqueValueInfos?.[0]?.value || r?.uniqueValueInfos?.[1]?.value);
    const $ = m.codedValues;
    return g(h) && ($ ? h = $.find((S) => h === S.code)?.name || h : h = this._getDisplayString(h, { useFieldFormatting: !0 })), p`<div class="section"><div class="title">${f.fieldSampleValue}</div><div class=${T(t === l.FAILED && i === l.FAILED && a === l.FAILED || !g(h) ? "missing" : "")}>${t === l.SUCCESS || i === l.SUCCESS || a === l.SUCCESS ? h?.toString() ?? v.allNulls : t === l.FAILED && i === l.FAILED && a === l.FAILED ? f.fieldSampleNotAvailable : f.fieldSampleRetrieving}</div></div>`;
  }
  renderFieldNumericFormat() {
    const { _messages: e, props: t, hideNumericFormat: i } = this, { fieldName: n, fieldInfo: a, layer: r } = t;
    if (i || !["double", "long", "single"].includes(a.layerField.type))
      return "";
    const f = this.originalLayerSupportsFieldConfiguration() ? r.getFieldConfiguration(n) : void 0;
    if (f?.fieldFormat) {
      const { minimumFractionDigits: c, maximumFractionDigits: o } = f.fieldFormat;
      return p`<div class="section"><div class="title">${e.fieldDecimalPlaces}</div><div>${e.fieldMinimumFractionDigits.replace("${number}", c.toString())}</div><div>${e.fieldMaximumFractionDigits.replace("${number}", o.toString())}</div></div>`;
    }
    const d = "popupTemplate" in r ? r.popupTemplate : void 0;
    if (d?.fieldInfos) {
      const c = d.fieldInfos?.filter((o) => o.fieldName === n);
      if (c?.length) {
        const o = c[0];
        if (g(o?.format?.places)) {
          const m = o.format.places;
          return p`<div class="section"><div class="title">${e.fieldDecimalPlaces}</div><div>${e.fieldNumDecimalPlaces.replace("${number}", m.toString())}</div></div>`;
        }
      }
    }
    return p`<div class="section"><div class="title">${e.fieldDecimalPlaces}</div><div class="missing">${e.fieldDecimalPlacesNotAvailable}</div></div>`;
  }
  renderFieldStatistics() {
    const { statisticsStatus: e, uniqueValuesStatus: t, hideStatistics: i, _messages: n, props: a } = this, { layer: r, fieldInfo: f } = a;
    return i ? (this.arcgisComplete.emit(), this.arcgisFieldInfoComplete.emit(), "") : ["stream", "imagery-tile", "voxel"].includes(r.type) || ["long"].includes(f.layerField.type) ? (this.arcgisComplete.emit(), this.arcgisFieldInfoComplete.emit(), "") : p`<div class="section"><div class="title">${n.fieldStatistics}</div>${!e || e === l.MISSING || e === l.IN_PROGRESS ? F("field-info-statistics-content", p`<div class="missing">${n.fieldStatisticsRetrieving}</div>`) : e === l.FAILED && t !== l.SUCCESS ? this.renderNoStatistics() : F("field-info-statistics-content", p`<div ${E(this._setCompleteRef)}>${this.renderStatistics()}</div>`)}</div>`;
  }
  renderNoStatistics() {
    const { _messages: e } = this;
    return F("field-info-statistics-content", p`<div class="missing" ${E(this._setCompleteRef)}>${e.fieldStatisticsNotAvailable}</div>`);
  }
  renderStatistics() {
    const { props: e } = this, { fieldInfo: t } = e;
    switch (this._getStatisticsType(t)) {
      case u.NUMBER:
        return this.renderNumberStatistics();
      case u.GUID:
      case u.OID:
      case u.STRING:
        return this.renderStringStatistics();
      case u.DATE:
      case u.DATE_ONLY:
      case u.TIME_ONLY:
      case u.TIMESTAMP_OFFSET:
        return this.renderDateStatistics();
      default:
        return "";
    }
  }
  renderNumberStatistics() {
    const { statistics: e, _messages: t } = this;
    if (!e)
      return this.renderNoStatistics();
    const { statistics: i } = t;
    return p`<div><div class="statistics-row"><div>${i.numberOfValues}</div><div class="data">${this._printNumValue(e.totalCount)}</div></div>${g(e.sum) ? p`<div class="statistics-row"><div>${i.sumOfValues}</div><div class="data">${this._printNumValue(e.sum)}</div></div>` : null}${g(e.min) ? p`<div class="statistics-row"><div>${i.minimum}</div><div class="data">${this._printNumValue(e.min)}</div></div>` : null}${g(e.max) ? p`<div class="statistics-row"><div>${i.maximum}</div><div class="data">${this._printNumValue(e.max)}</div></div>` : null}${g(e.avg) ? p`<div class="statistics-row"><div>${i.average}</div><div class="data">${this._printNumValue(e.avg)}</div></div>` : null}${g(e.stddev) ? p`<div class="statistics-row"><div>${i.standardDeviation}</div><div class="data">${this._printNumValue(e.stddev)}</div></div>` : null}${this.renderNullValues()}</div>`;
  }
  renderStringStatistics() {
    const { statistics: e, uniqueValuesStatus: t, _messages: i } = this, { statistics: n } = i;
    return p`<div><div class="statistics-row"><div>${n.numberOfValues}</div>${t !== l.SUCCESS ? p`<div class="missing">--</div>` : p`<div class="data">${this._printNumValue(e?.totalCount)}</div>`}</div>${this.renderNullValues()}${this.renderTopValues()}</div>`;
  }
  renderDateStatistics() {
    const { statistics: e, view: t, props: i, _messages: n } = this, { fieldInfo: a } = i;
    if (!e || !g(e.max) || !g(e.min))
      return this.renderNoStatistics();
    const { statistics: r } = n, f = e.max - e.min, d = Math.floor(f / 31536e6);
    let c = Math.floor((f - d * 31536e6) / 2628e6), o = Math.ceil((f - c * 2628e6) / 864e5);
    o >= 30 && (c += 1, o = 0);
    let m = d === 1 ? r.timeSpanOptions.year : d > 1 ? r.timeSpanOptions.years.replace("${years}", d.toString()) : "";
    m += d > 0 && (c > 0 || o > 0) ? ", " : "", m += c === 1 ? r.timeSpanOptions.month : c > 1 ? r.timeSpanOptions.months.replace("${months}", c.toString()) : "", m += c > 0 && o > 0 ? ", " : "", m += o === 1 ? r.timeSpanOptions.day : o > 1 ? r.timeSpanOptions.days.replace("${days}", o.toString()) : "";
    const v = a.simpleFieldType !== u.TIMESTAMP_OFFSET || !t || t.timeZone !== "unknown", h = a.simpleFieldType === u.TIME_ONLY;
    return p`<div><div class="statistics-row"><div>${r.numberOfValues}</div><div class="data">${this._printNumValue(e?.totalCount)}</div></div>${v && g(e.min) ? p`<div class="statistics-row"><div>${h ? r.minimumTime : r.minimumDate}</div><div class="data">${this._getDisplayString(e.min)}</div></div>` : null}${v && g(e.max) ? p`<div class="statistics-row"><div>${h ? r.maximumTime : r.maximumDate}</div><div class="data">${this._getDisplayString(e.max)}</div></div>` : null}${v && g(e.avg) ? p`<div class="statistics-row"><div>${h ? r.averageTime : r.averageDate}</div><div class="data">${this._getDisplayString(e.avg)}</div></div>` : null}${v && !h && g(e.min) && g(e.max) && f > 0 ? p`<div class="statistics-row"><div>${r.timespan}</div><div class="data">${m}</div></div>` : null}${this.renderNullValues()}</div>`;
  }
  renderTopValues() {
    const { uniqueValues: e, uniqueValuesStatus: t, _messages: i, props: n } = this, { fieldInfo: a } = n, { statistics: r } = i;
    if (e?.uniqueValueInfos?.length) {
      const f = e.uniqueValueInfos;
      f.sort((o, m) => o.count < m.count ? 1 : o.count > m.count ? -1 : 0);
      const d = a.codedValues, c = f.filter((o) => o.value !== null).filter((o, m) => o && m < 10).map((o) => {
        let m = o.value;
        return d ? d.forEach((v) => {
          m === v.code && (m = v.name);
        }) : m = this._getDisplayString(m), p`<div class="statistics-row"><div class="data">${`${m}`}</div><div class="count">${this._printNumValue(o.count)}</div></div>`;
      });
      return c.length ? p`<div><div class="statistics-row-top-values"><div>${f.length > 10 ? r.topTenValues : r.topValues}</div><div>${r.count}</div></div>${c}</div>` : "";
    } else
      return p`<div><div class="statistics-row-top-values"><div>${r.topValues}</div><div>${r.count}</div></div><div class="statistics-row"><div class="missing">${t === l.FAILED ? i.fieldUniqueValuesNotAvailable : i.fieldSampleRetrieving}</div></div></div>`;
  }
  renderNullValues() {
    const { statistics: e, uniqueValues: t, _messages: i } = this, { statistics: n } = i;
    let a = e?.nullcount;
    if (!g(a) && t) {
      const r = t.uniqueValueInfos;
      for (let f = 0; f < r.length; f++) {
        const d = r[f];
        if (d.value === null) {
          a = d.count;
          break;
        }
      }
    }
    return p`<div class="statistics-row"><div>${n.numberOfNulls}</div>${g(a) ? p`<div class="data">${this._printNumValue(a)}</div>` : p`<div class="missing">--</div>`}</div>`;
  }
}
A("arcgis-field-info", te);
export {
  te as ArcgisFieldInfo
};
