/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
import { c as w } from "../../chunks/runtime.js";
import { css as y, html as p } from "lit";
import { usePropertyChange as E } from "@arcgis/lumina/controllers";
import { classes as _ } from "@arcgis/toolkit/dom";
import { watch as u } from "@arcgis/core/core/reactiveUtils.js";
import { LitElement as C, createEvent as d, safeClassMap as m, nothing as P } from "@arcgis/lumina";
import { u as M } from "../../chunks/useT9n.js";
import { createRef as T, ref as O } from "lit/directives/ref.js";
import { m as L } from "../../chunks/useViewModel.js";
import { l as S } from "../../chunks/legacyIcon.js";
import { property as c, subclass as $ } from "@arcgis/core/core/accessorSupport/decorators.js";
import f from "@arcgis/core/core/Error.js";
import { onLocaleChange as D } from "@arcgis/core/intl.js";
import N from "@arcgis/core/PopupTemplate.js";
import x from "@arcgis/core/support/actions/ActionButton.js";
import { i as G } from "../../chunks/async-utils.js";
import { G as I, g as A } from "../../chunks/GeolocationPositioning.js";
import { g } from "../../chunks/globalCss.js";
const B = y`.arcgis-button{--calcite-icon-color: var(--calcite-color-text-3);--calcite-button-background-color: var(--calcite-color-foreground-1);color:var(--calcite-color-text-3);line-height:var(--calcite-font-line-height-relative-tight);calcite-button{--calcite-offset-invert-focus: 1}display:flex;flex-flow:column;cursor:pointer;background-color:var(--calcite-color-foreground-1);font-size:var(--calcite-font-size);:hover{--calcite-icon-color: var(--calcite-color-text-1);--calcite-button-background-color: var(--calcite-color-transparent-hover)}}:host{width:fit-content;height:fit-content}`;
var z = Object.defineProperty, V = Object.getOwnPropertyDescriptor, s = (e, t, o, a) => {
  for (var i = a > 1 ? void 0 : a ? V(t, o) : t, l = e.length - 1, n; l >= 0; l--)
    (n = e[l]) && (i = (a ? n(t, o, i) : n(i)) || i);
  return a && i && z(t, o, i), i;
};
const R = new x({
  icon: "trash",
  id: "remove-selected-feature",
  title: "{messages.remove}"
  // eslint-disable-next-line @typescript-eslint/no-deprecated
})._internalSetClassName("esri-icon-trash");
function U(e) {
  return new N({
    title: e.currentLocation,
    fieldInfos: [
      {
        fieldName: "timestamp",
        label: e.timestamp,
        format: {
          dateFormat: "short-date-short-time"
        }
      },
      {
        fieldName: "latitude",
        label: e.latitude,
        format: {
          places: 4,
          digitSeparator: !0
        }
      },
      {
        fieldName: "longitude",
        label: e.longitude,
        format: {
          places: 4,
          digitSeparator: !0
        }
      },
      {
        fieldName: "accuracy",
        label: e.accuracy,
        format: {
          places: 0,
          digitSeparator: !0
        }
      },
      {
        fieldName: "altitude",
        label: e.altitude,
        format: {
          places: 0,
          digitSeparator: !0
        }
      },
      {
        fieldName: "altitudeAccuracy",
        label: e.altitudeAccuracy,
        format: {
          places: 0,
          digitSeparator: !0
        }
      },
      {
        fieldName: "heading",
        label: e.heading,
        format: {
          places: 0,
          digitSeparator: !0
        }
      },
      {
        fieldName: "speed",
        label: e.speed,
        format: {
          places: 0,
          digitSeparator: !0
        }
      }
    ],
    actions: [R.clone()],
    content: [
      {
        type: "fields"
      }
    ]
  });
}
let r = class extends I {
  //#region Lifecycle
  constructor(e) {
    super(e), this._getCurrentPosition = A, this.popupEnabled = !0, this.locate = this.locate.bind(this);
  }
  initialize() {
    this.addHandles([
      D(() => {
        const { graphic: e, view: t } = this;
        if (!e)
          return;
        t?.graphics?.includes(e) && this._updatePopupTemplate(e);
      })
    ]);
  }
  destroy() {
    this.cancelLocate();
  }
  get state() {
    return this._geolocationUsable ? this.view?.ready ? this._locateController ? "locating" : this.error != null ? "error" : "ready" : "disabled" : "feature-unsupported";
  }
  //#endregion
  //#region Public Methods
  async locate() {
    if (this.cancelLocate(), this.state === "disabled")
      throw new f("locate:disabled-state", "Cannot locate when disabled.");
    if (this.state === "feature-unsupported")
      throw new f("locate:feature-unsupported-state", "Cannot locate in unsecure domain.");
    const e = new AbortController();
    this._locateController = e, this.error = void 0;
    try {
      const t = await this._getCurrentPosition(this.geolocationOptions);
      if (await this.updatePosition(t, e), this._locateController !== e)
        return null;
      const { graphic: o } = this;
      return o && this._updatePopupTemplate(o), this._addGraphic(), this.currentPosition = t, this._locateController = void 0, t;
    } catch (t) {
      if (G(t))
        return null;
      throw e === this._locateController && (this._locateController = void 0), this.error = t, t;
    }
  }
  cancelLocate() {
    this._clearGraphic(), this._locateController && this._locateController.abort(), this._locateController = void 0;
  }
  //#endregion
  //#region Private Methods
  _updatePopupTemplate(e) {
    if (!this.popupEnabled)
      return;
    const t = U(this.messages), o = e !== this.graphic;
    this.destroyed || o || (e.popupTemplate = t);
  }
  //#endregion
};
s([
  c()
], r.prototype, "_locateController", 2);
s([
  c()
], r.prototype, "currentPosition", 2);
s([
  c()
], r.prototype, "error", 2);
s([
  c()
], r.prototype, "messages", 2);
s([
  c()
], r.prototype, "popupEnabled", 2);
s([
  c({ readOnly: !0 })
], r.prototype, "state", 1);
r = s([
  $("map-components.locate.LocateViewModel")
], r);
const v = "gps-off", j = L(r);
class k extends C {
  constructor() {
    super(), this.locateButtonElement = T(), this.messages = M(), this.viewModel = j(this), this.hideErrorTooltip = () => {
      this.isErrorTooltipOpen = !1;
    }, this.isErrorTooltipOpen = !1, this.view = this.viewModel.view, this.autoDestroyDisabled = !1, this.geolocationOptions = this.viewModel.geolocationOptions, this.goToLocationDisabled = this.viewModel.goToLocationEnabled, this.goToOverride = this.viewModel.goToOverride, this.graphic = this.viewModel.graphic, this.icon = v, this.popupDisabled = this.viewModel.popupEnabled, this.scale = this.viewModel.scale, this.state = this.viewModel.state, this.visualScale = "m", this.arcgisError = d(), this.arcgisPropertyChange = E()("state"), this.arcgisReady = d(), this.arcgisSuccess = d(), this.listenOn(document, "click", this.hideErrorTooltip);
  }
  static {
    this.properties = { isErrorTooltipOpen: 16, view: 0, autoDestroyDisabled: 5, geolocationOptions: 0, goToLocationDisabled: 7, goToOverride: 0, graphic: 0, icon: 1, label: 1, messageOverrides: 0, popupDisabled: 5, referenceElement: 1, scale: 9, state: 32, visualScale: 1 };
  }
  static {
    this.styles = B;
  }
  async cancelLocate() {
    this.viewModel.cancelLocate();
  }
  async destroy() {
    await this.manager.destroy();
  }
  async locate() {
    return await this.viewModel.locate();
  }
  loaded() {
    this.viewModel.messages = { ...this.messages, ...this.messageOverrides }, this.manager.onLifecycle(() => [
      u(() => this.viewModel.error, (t) => {
        this.isErrorTooltipOpen = !!t, this.arcgisError.emit({ error: t });
      }),
      u(() => this.viewModel.currentPosition, (t) => {
        this.arcgisSuccess.emit({ position: t });
      })
    ]);
  }
  _localizeError(t) {
    if (t instanceof GeolocationPositionError)
      return t.code === GeolocationPositionError.PERMISSION_DENIED ? this.messages?.permissionError : t.code === GeolocationPositionError.TIMEOUT ? this.messages?.timeoutError : this.messages?.positionUnavailable;
    if (t instanceof Error)
      return t.message;
  }
  _locate() {
    const { viewModel: t } = this;
    t.state === "locating" ? t.cancelLocate() : t.locate().catch(() => {
    });
  }
  render() {
    const { viewModel: t, icon: o } = this, { state: a } = t, i = a === "locating", l = i ? this.messages.cancel : this.messages.title, n = a === "feature-unsupported", b = S === void 0 ? v : void 0, h = this._localizeError(this.viewModel?.error);
    return p`<div class=${m(_("root", g.arcgisButton))}>${!n && p`<calcite-button class=${m(g.widgetButton)} .disabled=${a === "disabled"} .loading=${i} .iconStart=${i ? void 0 : o ?? b} kind=neutral .label=${l} @click=${this._locate} .scale=${this.visualScale} title=${l ?? P} ${O(this.locateButtonElement)}></calcite-button>` || ""}${h ? p`<calcite-tooltip .open=${this.isErrorTooltipOpen} overlay-positioning=fixed .referenceElement=${this.locateButtonElement.value}>${h}</calcite-tooltip>` : null}</div>`;
  }
}
w("arcgis-locate", k);
export {
  k as ArcgisLocate
};
