/* COPYRIGHT Esri - https://js.arcgis.com/5.1/LICENSE.txt */
import { c as D } from "../../chunks/runtime.js";
import { css as q, html as d } from "lit";
import { keyed as v } from "lit/directives/keyed.js";
import { ref as T } from "lit/directives/ref.js";
import { LitElement as x, createEvent as b, safeClassMap as F } from "@arcgis/lumina";
import { Task as k } from "@lit/task";
import { log as V, composeMissingPropertyMessage as I } from "@arcgis/toolkit/log";
import E from "@arcgis/core/config.js";
import * as _ from "@arcgis/core/core/reactiveUtils.js";
import * as y from "@arcgis/core/intl.js";
import * as N from "@arcgis/core/applications/PortalApp/layerUtils.js";
import * as S from "@arcgis/core/core/lang.js";
import R from "@arcgis/core/smartMapping/statistics/summaryStatistics.js";
import A from "@arcgis/core/smartMapping/statistics/uniqueValues.js";
import L from "@arcgis/core/rest/support/Query.js";
import { u as Z } from "../../chunks/useT9n.js";
function p(a) {
  return a != null;
}
function P(a) {
  return a.type === "scene" ? a.associatedLayer?.url : a.url;
}
const M = {
  dateStyle: "short",
  timeStyle: "short"
}, U = {
  timeStyle: "medium"
};
function G(a) {
  const { layer: e, fieldName: t } = a;
  let i;
  const n = N.supportsFieldConfiguration(e);
  let s;
  "popupTemplate" in e && (s = e.popupTemplate);
  const r = s ? s.fieldInfos : [];
  return O(a)?.filter((u) => u.name === t).forEach((u) => {
    const l = !n && r ? r.filter((g) => g.fieldName === u.name) : null, o = n ? e.getFieldAlias(t) : l?.length ? l[0].label : u.alias;
    /^raster.(item|service)pixelvalue/iu.test(t) && (u.type = "double");
    const c = {
      layerField: u,
      label: o || u.name
    };
    c.codedValues = j(t, a), H(c), c.simpleFieldType && (i = c);
  }), i;
}
function O(a) {
  const { layer: e } = a;
  return e.type === "imagery-tile" || e.type === "wcs" || e.type === "imagery" && e.rasterFields.length ? e.rasterFields : e.fields;
}
async function C(a) {
  a.statisticsStatus = "in-progress";
  const { layer: e, view: t } = a;
  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 z(e, t);
  } catch {
    return;
  }
}
async function Q(a) {
  const { layer: e, view: t, fieldName: i, fieldInfo: n } = a;
  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 C(a), nullcount: 0 };
  try {
    const s = await R({
      layer: e,
      view: t,
      field: i,
      outStatisticTypes: { exclude: ["median"] }
    });
    if (!p(s.count))
      throw new Error("could not get statistics");
    const r = "sourceJSON" in e && e.sourceJSON.maxRecordCount === s.count;
    if (p(s.nullcount) && !r)
      return { ...s, totalCount: s.count + s.nullcount };
    {
      const m = await C(a);
      return { ...s, totalCount: m };
    }
  } catch {
    throw new Error("could not get statistics");
  }
}
async function W(a) {
  const { layer: e, view: t, fieldName: i } = a;
  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 A({
      layer: e,
      view: t,
      field: i
    });
  } catch {
    throw new Error("could not get unique values");
  }
}
function H(a) {
  switch (a.layerField.type) {
    case "string":
      a.simpleFieldType = "string";
      break;
    case "date":
      a.simpleFieldType = "date";
      break;
    case "timestamp-offset":
      a.simpleFieldType = "timestamp-offset";
      break;
    case "date-only":
      a.simpleFieldType = "date-only";
      break;
    case "time-only":
      a.simpleFieldType = "time-only";
      break;
    case "oid":
      a.simpleFieldType = "oid";
      break;
    case "guid":
    case "global-id":
      a.simpleFieldType = "guid";
      break;
    case "small-integer":
    case "big-integer":
    case "integer":
    case "single":
    case "double":
    case "long":
      a.simpleFieldType = "number";
      break;
  }
}
function j(a, e) {
  const { layer: t } = e;
  if (t.type === "subtype-sublayer" && t.subtypeField === a) {
    const l = t.parent?.subtypes?.find((o) => o.code === t.subtypeCode);
    if (l)
      return [{ code: l.code, name: l.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 s;
  const m = O(e)?.find((l) => l.name === a), u = m?.domain;
  return t.type === "feature" && i && n ? (i === a ? s = n.map(
    (l) => (
      // fake coded values
      {
        code: l.id,
        name: l.name
      }
    )
  ) : (s = [], n.forEach((l) => {
    if (!l.domains[a] || l.domains[a].type === "inherited") {
      const o = u;
      o?.codedValues && o.codedValues.forEach(async (c) => {
        let g = !1;
        s.forEach((f) => {
          f.code === c.code && (g = !0, `, ${f.name},`.includes(`, ${c.name},`) || (f.name += `, ${c.name}`));
        }), g || s.push(S.clone(c));
      });
    } else l.domains[a].codedValues && l.domains[a].codedValues.forEach(async (o) => {
      let c = !1;
      s.forEach((g) => {
        g.code === o.code && (c = !0, `, ${g.name},`.includes(`, ${o.name},`) || (g.name += `, ${o.name}`));
      }), c || s.push(S.clone(o));
    });
  })), !s.length && u?.codedValues && (s = S.clone(u.codedValues))) : u?.codedValues && (s = m.domain.codedValues), s?.length ? s : null;
}
async function J(a) {
  const { view: e, layer: t } = a;
  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(a);
    let i;
    if (t.type === "subtype-sublayer" || t.type === "sublayer") {
      let s = t.parent;
      for (; ["subtype-group", "map-image"].includes(s.type); )
        s = s.parent;
      i = await e.whenLayerView(s);
    } else
      i = await e.whenLayerView(t);
    if (i.availableFields.length === t.fields.length || ["stream", "ogc-feature"].includes(t.type) && i.availableFields.length > 0) {
      const s = t.createQuery();
      s.start = 0, s.num = 5, s.outFields = ["*"];
      const r = await i.queryFeatures(s);
      return r.features?.length ? r : await w(a);
    } else
      return await w(a);
  }
}
async function w(a) {
  const { layer: e } = a;
  if (["imagery", "imagery-tile", "stream", "ogc-feature"].includes(e.type))
    throw new Error("cannot get feature from service");
  const t = new L({
    where: "1=1",
    outFields: ["*"],
    returnGeometry: !1
  });
  return "sourceJSON" in e && e.sourceJSON?.advancedQueryCapabilities?.supportsPagination && (t.num = 1), await e.queryFeatures(t);
}
async function z(a, e) {
  if (a.type === "feature" && !a.url)
    return await B(a);
  if (a.type === "feature" || a.type === "csv" || a.type === "scene" || a.type === "wfs" || a.type === "geojson")
    return await a.queryFeatureCount();
  if (e && (a.type === "stream" || a.type === "ogc-feature"))
    return await K(a, e);
}
async function B(a) {
  const e = a.createQuery();
  e.outFields = ["*"];
  const t = await a.queryFeatures(e);
  if (t.features.length)
    return t.features.length;
  throw new Error("could not get feature count");
}
async function K(a, e) {
  return await (await e.whenLayerView(a)).queryFeatureCount();
}
const X = 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 Y extends x {
  constructor() {
    super(...arguments), this._messages = Z({ blocking: !0 }), this._propWatcherTask = new k(this, {
      task: async ([e, t]) => {
        const i = p(e) && p(t);
        if (p(e) || V("error", this, I("layer")), p(t) || V("error", this, I("fieldName")), !i)
          throw new Error();
        await this.processProps(), this._propWatcherTask.autoRun = !1;
      },
      args: () => [this.layer, this.fieldName]
    }), this.oneFeatureResponseStatus = "missing", this.statisticsStatus = "missing", this.uniqueValuesStatus = "missing", this.hideAlias = !1, this.hideNumericFormat = !1, this.hideStatistics = !1, this.arcgisComplete = b(), this.arcgisFieldInfoComplete = b();
  }
  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 = X;
  }
  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 s;
    if (t.declaredClass === "esri.layers.support.Sublayer") {
      const r = t;
      e && await _.whenOnce(() => !e.updating), s = await r.createFeatureLayer(), await s?.load();
    }
    this.props = {
      view: e,
      layer: s ?? t,
      fieldName: i,
      hideStatistics: n
    }, this.props.fieldInfo = G(this.props), t.type === "scene" && E.request.interceptors?.push({
      urls: `${P(t)}/${t.layerId}`,
      before(r) {
        r.requestOptions.authMode = "no-prompt";
      }
    }), this.oneFeatureResponseStatus = "in-progress";
    try {
      const r = await J(this.props);
      this.oneFeatureResponse = r, this.oneFeatureResponseStatus = "success";
    } catch {
      this.oneFeatureResponseStatus = "failed";
    }
    if (t.type === "stream") {
      this.uniqueValuesStatus = "failed", this.statisticsStatus = "failed";
      return;
    }
    if (n)
      this.uniqueValuesStatus = "failed";
    else {
      this.uniqueValuesStatus = "in-progress";
      try {
        const r = await W(this.props);
        this.uniqueValues = r, r?.uniqueValueInfos?.length ? this.uniqueValuesStatus = "success" : this.uniqueValuesStatus = "failed";
      } catch {
        this.uniqueValuesStatus = "failed";
      }
    }
    if (n)
      this.statisticsStatus = "failed";
    else {
      this.statisticsStatus = "in-progress";
      try {
        const r = await Q(this.props);
        if (!p(r.totalCount) && p(r.count) && this.uniqueValuesStatus === "success") {
          const m = this.uniqueValues?.uniqueValueInfos ?? [];
          for (let u = 0; u < m.length; u++) {
            const l = m[u];
            if (l.value === null) {
              r.totalCount = l.count + r.count;
              break;
            }
          }
          r.totalCount ??= r.count;
        }
        this.statistics = r, this.statisticsStatus = "success";
      } catch {
        this.statisticsStatus = "failed";
      }
    }
    this.setUpTimeZoneHandle();
  }
  setUpTimeZoneHandle() {
    this.timeZoneHandle?.remove();
    const { props: e } = this, { view: t, fieldInfo: i } = e;
    ["date", "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 "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 "string";
          default:
            return "number";
        }
      }
      case "date":
        return "date";
      case "date-only":
        return "date-only";
      case "string":
        return "string";
      case "time-only":
        return "time-only";
      case "timestamp-offset":
        return "timestamp-offset";
      default:
        return "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 "date":
        return this._getDateString(e, t);
      case "date-only":
        return this._getDateOnlyString(e, t);
      case "guid":
        return this._getGuidString(e);
      case "number":
        return this._getNumberString(e, t);
      case "time-only":
        return this._getTimeOnlyString(e, t);
      case "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 p(e) ? this._getNumberString(e, t) : "--";
  }
  _setCompleteRef() {
    this.arcgisComplete.emit(), this.arcgisFieldInfoComplete.emit();
  }
  getCurrentFieldFormat() {
    const { props: e } = this, { layer: t, fieldName: i } = e;
    return (this.originalLayerSupportsFieldConfigs() ? 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 ? U : M : 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 s = this.getPopupTemplateFieldInfo();
    return y.convertDateFormatToIntlOptions(s?.format?.dateFormat ?? e);
  }
  originalLayerSupportsFieldConfigs() {
    const { layer: e } = this;
    return N.supportsFieldConfiguration(e);
  }
  getPopupTemplateFieldInfo() {
    const { props: e } = this, { layer: t, fieldName: i } = e;
    return ("popupTemplate" in t ? t.popupTemplate : void 0)?.fieldInfos?.find((s) => s.fieldName === i);
  }
  render() {
    return this._propWatcherTask.render({
      complete: () => {
        const { props: e } = this, { fieldInfo: t } = e;
        return t ? d`<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 d`<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 ? "" : d`<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, s = n.layerField.description;
    return d`<div class="section"><div class="title">${e.fieldDescription}</div><div class=${F({
      missing: !s
    })}>${s || e.fieldDescriptionNotSet}</div></div>`;
  }
  renderFieldValueType() {
    const { _messages: e, props: t } = this, { layer: i } = t;
    if (i.type !== "feature")
      return "";
    const { fieldInfo: n } = t, s = this._getFieldValueTypeCamelCase(n);
    return d`<div class="section"><div class="title">${e.fieldValueType}</div><div class=${F(s ? "" : "missing")}>${s ? e.fieldValueTypes[s] : e.fieldValueTypeNotSet}</div></div>`;
  }
  renderFieldSampleValue() {
    const { oneFeatureResponse: e, oneFeatureResponseStatus: t, statisticsStatus: i, statistics: n, uniqueValuesStatus: s, uniqueValues: r, _messages: m, props: u } = this, { layer: l, fieldName: o, fieldInfo: c } = u, { statistics: g } = m;
    let f;
    if (["imagery-tile", "voxel"].includes(l.type) || l.type !== "stream" && ["string", "oid", "guid"].includes(this._getStatisticsType(c)) && s !== "failed")
      return "";
    t === "success" ? e.features.forEach((h) => {
      (f === void 0 || f === null && h.attributes[o] !== null) && (f = h.attributes[o]);
    }) : i === "success" ? f = n?.min : s === "success" && (f = r?.uniqueValueInfos?.[0]?.value || r?.uniqueValueInfos?.[1]?.value);
    const $ = c.codedValues;
    return p(f) && ($ ? f = $.find((h) => f === h.code)?.name || f : f = this._getDisplayString(f, { useFieldFormatting: !0 })), d`<div class="section"><div class="title">${m.fieldSampleValue}</div><div class=${F(t === "failed" && i === "failed" && s === "failed" || !p(f) ? "missing" : "")}>${t === "success" || i === "success" || s === "success" ? f?.toString() ?? g.allNulls : t === "failed" && i === "failed" && s === "failed" ? m.fieldSampleNotAvailable : m.fieldSampleRetrieving}</div></div>`;
  }
  renderFieldNumericFormat() {
    const { _messages: e, props: t, hideNumericFormat: i } = this, { fieldName: n, fieldInfo: s, layer: r } = t;
    if (i || !["double", "long", "single"].includes(s.layerField.type))
      return "";
    const m = this.originalLayerSupportsFieldConfigs() ? r.getFieldConfiguration(n) : void 0;
    if (m?.fieldFormat) {
      const { minimumFractionDigits: l, maximumFractionDigits: o } = m.fieldFormat;
      return d`<div class="section"><div class="title">${e.fieldDecimalPlaces}</div><div>${e.fieldMinimumFractionDigits.replace("${number}", l.toString())}</div><div>${e.fieldMaximumFractionDigits.replace("${number}", o.toString())}</div></div>`;
    }
    const u = "popupTemplate" in r ? r.popupTemplate : void 0;
    if (u?.fieldInfos) {
      const l = u.fieldInfos?.filter((o) => o.fieldName === n);
      if (l?.length) {
        const o = l[0];
        if (p(o?.format?.places)) {
          const c = o.format.places;
          return d`<div class="section"><div class="title">${e.fieldDecimalPlaces}</div><div>${e.fieldNumDecimalPlaces.replace("${number}", c.toString())}</div></div>`;
        }
      }
    }
    return d`<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: s } = this, { layer: r, fieldInfo: m } = s;
    return i ? (this.arcgisComplete.emit(), this.arcgisFieldInfoComplete.emit(), "") : ["stream", "imagery-tile", "voxel"].includes(r.type) || ["long"].includes(m.layerField.type) ? (this.arcgisComplete.emit(), this.arcgisFieldInfoComplete.emit(), "") : d`<div class="section"><div class="title">${n.fieldStatistics}</div>${!e || e === "missing" || e === "in-progress" ? v("field-info-statistics-content", d`<div class="missing">${n.fieldStatisticsRetrieving}</div>`) : e === "failed" && t !== "success" ? this.renderNoStatistics() : v("field-info-statistics-content", d`<div ${T(this._setCompleteRef)}>${this.renderStatistics()}</div>`)}</div>`;
  }
  renderNoStatistics() {
    const { _messages: e } = this;
    return v("field-info-statistics-content", d`<div class="missing" ${T(this._setCompleteRef)}>${e.fieldStatisticsNotAvailable}</div>`);
  }
  renderStatistics() {
    const { props: e } = this, { fieldInfo: t } = e;
    switch (this._getStatisticsType(t)) {
      case "number":
        return this.renderNumberStatistics();
      case "guid":
      case "oid":
      case "string":
        return this.renderStringStatistics();
      case "date":
      case "date-only":
      case "time-only":
      case "timestamp-offset":
        return this.renderDateStatistics();
      default:
        return "";
    }
  }
  renderNumberStatistics() {
    const { statistics: e, _messages: t } = this;
    if (!e)
      return this.renderNoStatistics();
    const { statistics: i } = t;
    return d`<div><div class="statistics-row"><div>${i.numberOfValues}</div><div class="data">${this._printNumValue(e.totalCount)}</div></div>${p(e.sum) ? d`<div class="statistics-row"><div>${i.sumOfValues}</div><div class="data">${this._printNumValue(e.sum)}</div></div>` : null}${p(e.min) ? d`<div class="statistics-row"><div>${i.minimum}</div><div class="data">${this._printNumValue(e.min)}</div></div>` : null}${p(e.max) ? d`<div class="statistics-row"><div>${i.maximum}</div><div class="data">${this._printNumValue(e.max)}</div></div>` : null}${p(e.avg) ? d`<div class="statistics-row"><div>${i.average}</div><div class="data">${this._printNumValue(e.avg)}</div></div>` : null}${p(e.stddev) ? d`<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 d`<div><div class="statistics-row"><div>${n.numberOfValues}</div>${t !== "success" ? d`<div class="missing">--</div>` : d`<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: s } = i;
    if (!e || !p(e.max) || !p(e.min))
      return this.renderNoStatistics();
    const { statistics: r } = n, m = e.max - e.min, u = Math.floor(m / 31536e6);
    let l = Math.floor((m - u * 31536e6) / 2628e6), o = Math.ceil((m - l * 2628e6) / 864e5);
    o >= 30 && (l += 1, o = 0);
    let c = u === 1 ? r.timeSpanOptions.year : u > 1 ? r.timeSpanOptions.years.replace("${years}", u.toString()) : "";
    c += u > 0 && (l > 0 || o > 0) ? ", " : "", c += l === 1 ? r.timeSpanOptions.month : l > 1 ? r.timeSpanOptions.months.replace("${months}", l.toString()) : "", c += l > 0 && o > 0 ? ", " : "", c += o === 1 ? r.timeSpanOptions.day : o > 1 ? r.timeSpanOptions.days.replace("${days}", o.toString()) : "";
    const g = s.simpleFieldType !== "timestamp-offset" || !t || t.timeZone !== "unknown", f = s.simpleFieldType === "time-only";
    return d`<div><div class="statistics-row"><div>${r.numberOfValues}</div><div class="data">${this._printNumValue(e?.totalCount)}</div></div>${g && p(e.min) ? d`<div class="statistics-row"><div>${f ? r.minimumTime : r.minimumDate}</div><div class="data">${this._getDisplayString(e.min)}</div></div>` : null}${g && p(e.max) ? d`<div class="statistics-row"><div>${f ? r.maximumTime : r.maximumDate}</div><div class="data">${this._getDisplayString(e.max)}</div></div>` : null}${g && p(e.avg) ? d`<div class="statistics-row"><div>${f ? r.averageTime : r.averageDate}</div><div class="data">${this._getDisplayString(e.avg)}</div></div>` : null}${g && !f && p(e.min) && p(e.max) && m > 0 ? d`<div class="statistics-row"><div>${r.timespan}</div><div class="data">${c}</div></div>` : null}${this.renderNullValues()}</div>`;
  }
  renderTopValues() {
    const { uniqueValues: e, uniqueValuesStatus: t, _messages: i, props: n } = this, { fieldInfo: s } = n, { statistics: r } = i;
    if (e?.uniqueValueInfos?.length) {
      const m = e.uniqueValueInfos;
      m.sort((o, c) => o.count < c.count ? 1 : o.count > c.count ? -1 : 0);
      const u = s.codedValues, l = m.filter((o) => o.value !== null).filter((o, c) => o && c < 10).map((o) => {
        let c = o.value;
        return u ? u.forEach((g) => {
          c === g.code && (c = g.name);
        }) : c = this._getDisplayString(c), d`<div class="statistics-row"><div class="data">${`${c}`}</div><div class="count">${this._printNumValue(o.count)}</div></div>`;
      });
      return l.length ? d`<div><div class="statistics-row-top-values"><div>${m.length > 10 ? r.topTenValues : r.topValues}</div><div>${r.count}</div></div>${l}</div>` : "";
    } else
      return d`<div><div class="statistics-row-top-values"><div>${r.topValues}</div><div>${r.count}</div></div><div class="statistics-row"><div class="missing">${t === "failed" ? i.fieldUniqueValuesNotAvailable : i.fieldSampleRetrieving}</div></div></div>`;
  }
  renderNullValues() {
    const { statistics: e, uniqueValues: t, _messages: i } = this, { statistics: n } = i;
    let s = e?.nullcount;
    if (!p(s) && t) {
      const r = t.uniqueValueInfos;
      for (let m = 0; m < r.length; m++) {
        const u = r[m];
        if (u.value === null) {
          s = u.count;
          break;
        }
      }
    }
    return d`<div class="statistics-row"><div>${n.numberOfNulls}</div>${p(s) ? d`<div class="data">${this._printNumValue(s)}</div>` : d`<div class="missing">--</div>`}</div>`;
  }
}
D("arcgis-field-info", Y);
export {
  Y as ArcgisFieldInfo
};
