/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
import { c as m } from "../../chunks/runtime.js";
import { css as f, html as d } from "lit";
import { watch as p } from "@arcgis/core/core/reactiveUtils.js";
import { LitElement as _, createEvent as g, safeClassMap as w, nothing as k } from "@arcgis/lumina";
import { usePropertyChange as b } from "@arcgis/lumina/controllers";
import { classes as T } from "@arcgis/toolkit/dom";
import { u as y } from "../../chunks/useT9n.js";
import { m as M } from "../../chunks/useViewModel.js";
import { g as P } from "../../chunks/globalCss.js";
import { property as a, subclass as E } from "@arcgis/core/core/accessorSupport/decorators.js";
import { i as I, b as O } from "../../chunks/async-utils.js";
import { debounce as C } from "lodash-es";
import { G as S } from "../../chunks/GeolocationPositioning.js";
const D = f`.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 F = Object.defineProperty, $ = Object.getOwnPropertyDescriptor, r = (e, t, s, c) => {
  for (var i = c > 1 ? void 0 : c ? $(t, s) : t, h = e.length - 1, l; h >= 0; h--)
    (l = e[h]) && (i = (c ? l(t, s, i) : l(i)) || i);
  return c && i && F(t, s, i), i;
};
const x = 15e3;
let o = class extends S {
  constructor(e) {
    super(e);
  }
  destroy() {
    this._stopTracking();
  }
  get state() {
    return this._geolocationUsable ? this.view && !this.view.ready ? "disabled" : this._settingPosition || this._trackStartingTimeoutId !== void 0 ? "waiting" : this.tracking ? "tracking" : this.error != null ? "error" : "ready" : "feature-unsupported";
  }
  get tracking() {
    return this._watchId !== void 0;
  }
  start() {
    this.state === "disabled" || this.state === "feature-unsupported" || this._startTracking();
  }
  stop() {
    this.state === "disabled" || this.state === "feature-unsupported" || this._stopTracking();
  }
  _stopWatchingPosition() {
    this._watchId !== void 0 && (navigator.geolocation.clearWatch(this._watchId), this._watchId = void 0);
  }
  _stopTracking() {
    this._abortTrack(), this._clearWaitingTimer(), this._stopWatchingPosition(), this._clearGraphic();
  }
  _startTracking() {
    this._stopTracking();
    const e = C(async (t) => {
      this._abortTrack();
      const s = new AbortController();
      this._trackController = s;
      const { timestamp: c, coords: i } = t, h = i.toJSON(), l = {
        timestamp: c,
        coords: h
      };
      this.error = void 0;
      try {
        const n = this.positionFilterFunction;
        if (typeof n == "function" && !n({ position: l }) || (await this.updatePosition(t, s), this._trackController !== s))
          return;
        this._clearWaitingTimer(), this._addGraphic(), this.currentPosition = t, this._trackController = void 0;
      } catch (n) {
        if (I(n))
          return;
        throw this._trackController = void 0, this.error = n, this._clearWaitingTimer(), n;
      }
    }, 0);
    this._watchId = navigator.geolocation.watchPosition(
      (t) => {
        this._settingPosition = e(t)?.catch(O);
      },
      this._handleWatchPositionError.bind(this),
      this.geolocationOptions ?? void 0
    ), this._trackStartingTimeoutId = setTimeout(() => {
      this._trackStartingTimeoutId = void 0;
    }, x);
  }
  _handleWatchPositionError(e) {
    e.code === e.PERMISSION_DENIED && this._stopTracking(), this.error = e;
  }
  _abortTrack() {
    this._trackController?.abort(), this._trackController = void 0;
  }
  _clearWaitingTimer() {
    clearTimeout(this._trackStartingTimeoutId), this._trackStartingTimeoutId = void 0, this._settingPosition = void 0;
  }
};
r([
  a()
], o.prototype, "_watchId", 2);
r([
  a()
], o.prototype, "_trackStartingTimeoutId", 2);
r([
  a()
], o.prototype, "_settingPosition", 2);
r([
  a()
], o.prototype, "currentPosition", 2);
r([
  a()
], o.prototype, "error", 2);
r([
  a()
], o.prototype, "positionFilterFunction", 2);
r([
  a({ readOnly: !0 })
], o.prototype, "state", 1);
r([
  a({ readOnly: !0 })
], o.prototype, "tracking", 1);
r([
  a()
], o.prototype, "start", 1);
r([
  a()
], o.prototype, "stop", 1);
o = r([
  E("map-components.track.TrackViewModel")
], o);
const W = M(o);
class G extends _ {
  constructor() {
    super(...arguments), this.messages = y(), this.viewModel = W(this), this.view = this.viewModel.view, this.autoDestroyDisabled = !1, this.currentPosition = this.viewModel.currentPosition, this.error = this.viewModel.error, this.geolocationOptions = this.viewModel.geolocationOptions, this.goToOverride = this.viewModel.goToOverride, this.goToLocationDisabled = this.viewModel.goToLocationEnabled, this.graphic = this.viewModel.graphic, this.icon = "compass-north-circle", this.positionFilterFunction = this.viewModel.positionFilterFunction, this.rotationDisabled = this.viewModel.rotationEnabled, this.scale = this.viewModel.scale, this.state = this.viewModel.state, this.tracking = this.viewModel.tracking, this.visualScale = "m", this.arcgisComplete = g(), this.arcgisError = g(), this.arcgisPropertyChange = b()("state"), this.arcgisReady = g();
  }
  static {
    this.properties = { view: 0, autoDestroyDisabled: 5, currentPosition: 0, error: 0, geolocationOptions: 0, goToOverride: 0, goToLocationDisabled: 7, graphic: 0, icon: 1, label: 1, messageOverrides: 0, positionFilterFunction: 0, referenceElement: 1, rotationDisabled: 5, scale: 9, state: 0, tracking: 36, visualScale: 1 };
  }
  static {
    this.styles = D;
  }
  async destroy() {
    await this.manager.destroy();
  }
  async start() {
    this.viewModel.start();
  }
  async stop() {
    this.viewModel.stop();
  }
  loaded() {
    this.manager.onLifecycle(() => [
      p(() => this.viewModel.error, (t) => {
        this.arcgisError.emit({ error: t });
      }),
      p(() => this.viewModel.currentPosition, (t) => {
        this.arcgisComplete.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;
  }
  _toggleTracking() {
    if (!this.viewModel)
      return;
    const { state: t } = this.viewModel;
    if (!(t === "feature-unsupported" || t === "disabled")) {
      if (t === "tracking" || t === "waiting") {
        this.viewModel.stop();
        return;
      }
      this.viewModel.start();
    }
  }
  render() {
    const { viewModel: t, messages: s, icon: c } = this, i = t?.state, h = i === "tracking", l = this._localizeError(this.viewModel?.error), n = (h ? s?.stopTracking : s?.startTracking) ?? "", u = i === "feature-unsupported", v = (i === "tracking" ? "pause" : void 0) ?? c ?? void 0;
    return d`<div class=${w(T("root", P.arcgisButton))}>${!u && d`<calcite-button .disabled=${i === "disabled"} .iconStart=${v} kind=neutral .label=${n} .loading=${i === "waiting"} @click=${this._toggleTracking} .scale=${this.visualScale} title=${n ?? k}></calcite-button>` || ""}${l ? d`<calcite-tooltip open overlay-positioning=fixed .referenceElement=${this.el}>${l}</calcite-tooltip>` : null}</div>`;
  }
}
m("arcgis-track", G);
export {
  G as ArcgisTrack
};
