import { c as I } from "../../chunks/runtime.js";
import { html as m } from "lit-html";
import { usePropertyChange as G } from "@arcgis/lumina/controllers";
import { classes as F } from "@arcgis/components-utils";
import { watch as y } from "@geoscene/core/core/reactiveUtils.js";
import { LitElement as z, createEvent as f, noShadowRoot as j, safeClassMap as w, nothing as Q } from "@arcgis/lumina";
import { u as V } from "../../chunks/useT9n.js";
import { m as k } from "../../chunks/useViewModel.js";
import { g as b } from "../../chunks/globalCss.js";
import { l as H } from "../../chunks/legacyIcon.js";
import { css as K } from "@lit/reactive-element/css-tag.js";
import { property as n, subclass as S } from "@geoscene/core/core/accessorSupport/decorators.js";
import u from "@geoscene/core/core/Error.js";
import { onLocaleChange as J } from "@geoscene/core/intl.js";
import q from "@geoscene/core/PopupTemplate.js";
import W from "@geoscene/core/support/actions/ActionButton.js";
import { t as X, a as E } from "../../chunks/async-utils.js";
import B from "@geoscene/core/core/Accessor.js";
import O from "@geoscene/core/Graphic.js";
import Z from "@geoscene/core/symbols/CIMSymbol.js";
import Y from "@geoscene/core/geometry/Point.js";
import * as A from "@geoscene/core/geometry/operators/projectOperator.js";
import P from "@geoscene/core/config.js";
import { geographicToWebMercator as $ } from "@geoscene/core/geometry/support/webMercatorUtils.js";
import ee from "@geoscene/core/portal/Portal.js";
import { project as te } from "@geoscene/core/rest/geometryService.js";
import oe from "@geoscene/core/rest/support/ProjectParameters.js";
/*! All material copyright GeoScene, All Rights Reserved, unless otherwise specified.
See https://js.geoscene.cn/4.33/geoscene/copyright.txt for details.
v4.33.18 */
const ie = K`@layer{geoscene-locate{display:block}}`;
let M = !1;
const re = {
  maximumAge: 0,
  timeout: 15e3,
  enableHighAccuracy: !0
};
function ae() {
  const e = "geolocation" in navigator;
  return e || console.warn("geolocation-unsupported", "Geolocation unsupported."), e;
}
function se() {
  const e = window.isSecureContext;
  return e || M || (M = !0, console.warn("insecure-context", "Geolocation requires a secure origin.")), e;
}
function ne() {
  return ae() && se();
}
function ce(e) {
  return e ??= re, new Promise((o, r) => {
    setTimeout(
      () => r(new u("geolocation:timeout", "getting the current geolocation position timed out")),
      e?.timeout ?? 15e3
    ), navigator.geolocation.getCurrentPosition(o, r, e ?? void 0);
  });
}
function le(e, t) {
  const { position: o, view: r } = e, a = pe(o)?.coords;
  if (!a)
    throw new u("geometry-service:no-coords", "Geolocation has no coordinates");
  const s = de(a);
  return ue(s, r, t);
}
function pe(e) {
  const t = e?.coords || {}, o = {
    accuracy: t.accuracy,
    altitude: t.altitude,
    altitudeAccuracy: t.altitudeAccuracy,
    heading: t.heading,
    latitude: t.latitude,
    longitude: t.longitude,
    speed: t.speed,
    toJSON() {
      return {};
    }
  };
  return e && {
    coords: o,
    timestamp: e.timestamp,
    toJSON() {
      return {};
    }
  };
}
function de({ longitude: e, latitude: t, altitude: o }) {
  return new Y({
    longitude: e,
    latitude: t,
    z: o || void 0,
    spatialReference: {
      wkid: 4326
    }
  });
}
async function ue(e, t, o) {
  if (!t)
    return await Promise.resolve(e);
  const r = t.spatialReference;
  return r.isWGS84 ? await Promise.resolve(e) : r.isWebMercator ? await Promise.resolve($(e)) : A.isLoaded() ? await Promise.resolve(A.execute(e, r)) : await he(o).then(async (i) => {
    if (!i)
      throw new u("geometry-service:missing-url", "Geometry service URL is missing");
    const a = new oe({
      geometries: [e],
      outSpatialReference: r
    });
    return (await te(i, a, o))[0];
  });
}
async function he(e) {
  if (P.geometryServiceUrl)
    return await Promise.resolve(P.geometryServiceUrl);
  const t = ee.getDefault();
  try {
    await t.load(e);
  } catch {
  }
  return t.helperServices?.geometry?.url;
}
var me = Object.defineProperty, ge = Object.getOwnPropertyDescriptor, p = (e, t, o, r) => {
  for (var i = r > 1 ? void 0 : r ? ge(t, o) : t, a = e.length - 1, s; a >= 0; a--)
    (s = e[a]) && (i = (r ? s(t, o, i) : s(i)) || i);
  return r && i && me(t, o, i), i;
};
const fe = 2500;
function T(e) {
  const t = {
    type: "CIMVectorMarker",
    enable: !0,
    anchorPoint: {
      x: 0,
      y: 0
    },
    anchorPointUnits: "Relative",
    dominantSizeAxis3D: "Y",
    size: e === "background" ? 16 : 14,
    billboardMode3D: "FaceNearPlane",
    frame: {
      xmin: 0,
      ymin: 0,
      xmax: 17,
      ymax: 17
    },
    markerGraphics: [
      {
        type: "CIMMarkerGraphic",
        geometry: {
          rings: [
            [
              [8.5, 0],
              [7.02, 0.13],
              [5.59, 0.51],
              [4.25, 1.14],
              [3.04, 1.99],
              [1.99, 3.04],
              [1.14, 4.25],
              [0.51, 5.59],
              [0.13, 7.02],
              [0, 8.5],
              [0.13, 9.98],
              [0.51, 11.41],
              [1.14, 12.75],
              [1.99, 13.96],
              [3.04, 15.01],
              [4.25, 15.86],
              [5.59, 16.49],
              [7.02, 16.87],
              [8.5, 17],
              [9.98, 16.87],
              [11.41, 16.49],
              [12.75, 15.86],
              [13.96, 15.01],
              [15.01, 13.96],
              [15.86, 12.75],
              [16.49, 11.41],
              [16.87, 9.98],
              [17, 8.5],
              [16.87, 7.02],
              [16.49, 5.59],
              [15.86, 4.25],
              [15.01, 3.04],
              [13.96, 1.99],
              [12.75, 1.14],
              [11.41, 0.51],
              [9.98, 0.13],
              [8.5, 0]
            ]
          ]
        },
        symbol: {
          type: "CIMPolygonSymbol",
          symbolLayers: [
            {
              type: "CIMSolidStroke",
              enable: !0,
              capStyle: "Round",
              joinStyle: "Round",
              lineStyle3D: "Strip",
              miterLimit: 10,
              width: e === "background" ? 0 : 2,
              color: [255, 255, 255, 255]
            },
            {
              type: "CIMSolidFill",
              enable: !0,
              color: e === "background" ? [0, 0, 0, 66] : [0, 122, 194, 255]
            }
          ]
        }
      }
    ],
    scaleSymbolsProportionally: !0,
    respectFrame: !0
  };
  return e === "background" && (t.offsetX = 0, t.offsetY = -1), t;
}
const L = {
  type: "CIMPictureMarker",
  primitiveName: "headingOverride",
  enable: !0,
  anchorPoint: {
    x: 0,
    y: -0.5
  },
  anchorPointUnits: "Relative",
  dominantSizeAxis3D: "Y",
  size: 36,
  billboardMode3D: "FaceNearPlane",
  invertBackfaceTexture: !0,
  scaleX: 1,
  textureFilter: "Picture",
  url: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAkCAYAAACe0YppAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAYaSURBVHgBvVfNb1VFFD/nzP16xRYJKYREEiJoDLLShQkrSNzoHv8I2QgxwY8FJWHhxoVxISEu2AordWNiQjAxEBeEsKAmhCCwkPDRAn1t33v33jnH37n3Fam0pa8kTjOde+/MnN/5+J0z85jW08yYTpxgfzx0bS+fO0R0YHqyeb9w7YEtLTv+9rSdOH7ciNleJJJX/Do1JQ3AltdlT35fiN6gG8kD8akdmzO+6w/zM7wdw725rUY78DBXtmATA6PZntFgm9Kjm6o/HFJpdi5Xhp+16sDBC+H+gUmZfjIXHKC+35U42ZHZfpe30BZS7okNFnhu8wTRk2ek5LEV2q+N8nEj6yuNVRjHddftrt4ahyJbOxF+Uppi/Rf47NlA05Pp9vkyRNkkD8sqUJHwOGfSpYFQFXhTJryQBaZSeAxbFus+U1K0gJm2oy3QKwuZzqeuSK5kpW6BEsE6+nCsAHDXQWuaOljzU8uP/ToxUW4KcwKg8QzOSdFL6Swm0hurAC7N2qIW7ncwNgYKF4la3/w7RnzrUK29KseXWqmTKXGl45Zrd9CLrsSjr96fcw4kS46mTsJznSTrVBR6VQJQdDbpZTWexxgCYCFz30cquD8oYVQgtUAUzfo8wGtqGoNRFmFZ1KKulJMQu3Vpm/I8Pup3ekvES57GaabXo4lsszEA6zrkhcmAAkBNshi59O9wVsokBLZUCQAxllXVBkyCDRQuTlLLiLSEqw3gfUqU0kVdsKymsnzyPLm8fXZxDxVZgvUhg9QyaKDI7AhpSlRVEaA83JM+/V8pGO0PMTHyZwra9FQVk4i1e0D6dPK9v5agkmXAhc0Bw5MjlAQQE0lSDbUmbBX4kGfsiiQWuSZtdle1S4F73cUKJgviyw4mmmqlVSoR/FAK2d1noWQZ8N79MySw0tg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RXh2+36eOt+2nENrrF3ozODEmFC0D4hjbQNgYc+DSYjd9qqGSJXqL/tZ16/DWdfvw9bbCt41hcpYn9RAEX9Q22fwC74ny5v9iplQAAAABJRU5ErkJggg=="
}, ye = T("layer"), ve = T("background"), we = new Z({
  data: {
    type: "CIMSymbolReference",
    symbol: {
      type: "CIMPointSymbol",
      symbolLayers: [ye, ve, L],
      angleAlignment: "Map"
    },
    primitiveOverrides: [
      {
        type: "CIMPrimitiveOverride",
        primitiveName: "headingOverride",
        propertyName: "Rotation",
        valueExpressionInfo: {
          type: "CIMExpressionInfo",
          title: "Rotation override",
          expression: "360 - $feature.heading",
          returnType: "Default"
        }
      },
      {
        type: "CIMPrimitiveOverride",
        primitiveName: "headingOverride",
        propertyName: "TintColor",
        valueExpressionInfo: {
          type: "CIMExpressionInfo",
          title: "TintColor override",
          expression: "IIF(IsEmpty($feature.heading), [255, 255, 255, 0], [255, 255, 255, 1])",
          returnType: "Default"
        }
      }
    ]
  }
});
let c = class extends B {
  constructor() {
    super(...arguments), this._geolocationUsable = !0, this.goToLocationEnabled = !0, this.graphic = new O({
      symbol: we
    }), this.rotationEnabled = !0;
  }
  //#region Lifecycle
  initialize() {
    ne() || (this._geolocationUsable = !1), this.addHandles([
      y(
        () => this.view?.type,
        () => this._handleViewTypeChange(),
        {
          initial: !0
        }
      )
    ]);
  }
  destroy() {
    this._clearGraphic(), this.view = void 0;
  }
  //#endregion
  //#region Private Methods
  /**
   * Clears the locate graphic from the view.
   */
  _clearGraphic() {
    const { view: e, graphic: t } = this;
    e && t && e.graphics.remove(t);
  }
  /**
   * Adds the graphic to the view.
   */
  _addGraphic() {
    const { view: e, graphic: t } = this;
    !e?.graphics || !t || e.graphics.includes(t) || e.graphics.push(t);
  }
  _handleViewTypeChange() {
    L.enable = this.view?.type === "2d";
  }
  _getScaleWithinConstraints(e, t) {
    if (!t)
      return e;
    if (t.type === "2d") {
      const { effectiveMaxScale: o, effectiveMinScale: r } = t.constraints;
      return Math.min(r, Math.max(o, e));
    }
    return e;
  }
  _getScale(e) {
    const { scale: t } = this, o = typeof t == "number" ? t : fe;
    return this._getScaleWithinConstraints(o, e);
  }
  _getHeading(e, t) {
    const o = t?.spatialReference, r = o?.isWebMercator || o?.isGeographic, i = e.coords?.heading;
    return !r || typeof i != "number" || Number.isNaN(i) || i < 0 || i > 360 ? null : i;
  }
  _addHeading(e) {
    const { heading: t, target: o, view: r } = e;
    if (!(!r || t === null)) {
      if (r.type === "3d") {
        o.heading = t;
        return;
      }
      r.type === "2d" && (o.rotation = 360 - t);
    }
  }
  async _animatePoint(e, t, o, r) {
    const { view: i } = this;
    if (!this.goToLocationEnabled || !i)
      return;
    const a = {
      target: e,
      scale: t
    };
    this.rotationEnabled && this._addHeading({
      heading: o,
      target: a,
      view: i
    });
    const s = { signal: r.signal };
    X(s), this.goToOverride && i && this.goToOverride(i, {
      target: a,
      options: s
    }), await i.goTo(a, s);
  }
  async updatePosition(e, t) {
    try {
      const o = this.view, r = await le({ position: e, view: o }, { signal: t.signal }), { graphic: i } = this, { timestamp: a, coords: s } = e, { accuracy: g, altitude: h, altitudeAccuracy: N, latitude: D, longitude: x, speed: R } = s, v = this._getHeading(e, o), U = {
        timestamp: a,
        accuracy: g,
        altitude: h,
        altitudeAccuracy: N,
        heading: v,
        latitude: D,
        longitude: x,
        speed: R
      };
      i && (i.geometry = r, i.attributes = U);
      const _ = this._getScale(o);
      await this._animatePoint(r, _, v, t);
    } catch (o) {
      if (!E(o))
        throw new u("geolocation-positioning:invalid-point", "Cannot position invalid point", {
          error: o
        });
    }
    return e;
  }
  //#endregion
};
p([
  n()
], c.prototype, "_geolocationUsable", 2);
p([
  n()
], c.prototype, "geolocationOptions", 2);
p([
  n()
], c.prototype, "goToLocationEnabled", 2);
p([
  n()
], c.prototype, "goToOverride", 2);
p([
  n({
    type: O
  })
], c.prototype, "graphic", 2);
p([
  n()
], c.prototype, "scale", 2);
p([
  n()
], c.prototype, "rotationEnabled", 2);
p([
  n()
], c.prototype, "view", 2);
c = p([
  S("map-components.geolocation.GeolocationPositioning")
], c);
var be = Object.defineProperty, Ae = Object.getOwnPropertyDescriptor, d = (e, t, o, r) => {
  for (var i = r > 1 ? void 0 : r ? Ae(t, o) : t, a = e.length - 1, s; a >= 0; a--)
    (s = e[a]) && (i = (r ? s(t, o, i) : s(i)) || i);
  return r && i && be(t, o, i), i;
};
const Pe = new W({
  icon: "trash",
  id: "remove-selected-feature",
  title: "{messages.remove}",
  className: "geoscene-icon-trash"
});
function Me(e) {
  return new q({
    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: [Pe.clone()],
    content: [
      {
        type: "fields"
      }
    ]
  });
}
let l = class extends c {
  //#region Lifecycle
  constructor(e) {
    super(e), this._locateController = null, this.currentPosition = null, this.error = void 0, this.messages = null, this.popupEnabled = !0, this.locate = this.locate.bind(this);
  }
  initialize() {
    this.addHandles([
      J(() => {
        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 u("locate:disabled-state", "Cannot locate when disabled.");
    if (this.state === "feature-unsupported")
      throw new u("locate:feature-unsupported-state", "Cannot locate in unsecure domain.");
    const e = new AbortController();
    this._locateController = e, this.error = void 0;
    try {
      const t = await ce(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 = null, t;
    } catch (t) {
      if (E(t))
        return null;
      throw e === this._locateController && (this._locateController = null), this.error = t, t;
    }
  }
  cancelLocate() {
    this._clearGraphic(), this._locateController && this._locateController.abort(), this._locateController = null;
  }
  //#endregion
  //#region Private Methods
  _updatePopupTemplate(e) {
    if (!this.popupEnabled)
      return;
    const t = Me(this.messages), o = e !== this.graphic;
    this.destroyed || o || (e.popupTemplate = t);
  }
  //#endregion
};
d([
  n()
], l.prototype, "_locateController", 2);
d([
  n()
], l.prototype, "currentPosition", 2);
d([
  n()
], l.prototype, "error", 2);
d([
  n()
], l.prototype, "messages", 2);
d([
  n()
], l.prototype, "popupEnabled", 2);
d([
  n({ readOnly: !0 })
], l.prototype, "state", 1);
l = d([
  S("map-components.locate.LocateViewModel")
], l);
const Ce = {
  base: "geoscene-locate"
}, C = "gps-off", Se = k(l);
class Ee extends z {
  constructor() {
    super(...arguments), this.messages = V(), this.viewModel = Se(this), 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 = C, this.popupDisabled = this.viewModel.popupEnabled, this.position = "top-left", this.scale = this.viewModel.scale, this.state = this.viewModel.state, this.geosceneError = f(), this.geoscenePropertyChange = G()("state"), this.geosceneReady = f(), this.geosceneSuccess = f();
  }
  static {
    this.properties = { autoDestroyDisabled: 5, geolocationOptions: 0, goToLocationDisabled: 7, goToOverride: 0, graphic: 0, icon: 1, label: 1, messageOverrides: 0, popupDisabled: 5, position: 3, referenceElement: 1, scale: 9, state: 3 };
  }
  static {
    this.shadowRootOptions = j;
  }
  static {
    this.styles = ie;
  }
  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(() => [
      y(() => this.viewModel.error, (t) => {
        this.geosceneError.emit({ error: t });
      }),
      y(() => this.viewModel.currentPosition, (t) => {
        this.geosceneSuccess.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: r } = t, i = r === "locating", a = i ? this.messages.cancel : this.messages.title, s = r === "feature-unsupported", g = H === void 0 ? C : void 0, h = this._localizeError(this.viewModel?.error);
    return m`<div class=${w(F(Ce.base, b.widget))}>${!s && m`<calcite-button class=${w(b.widgetButton)} .disabled=${r === "disabled"} .iconStart=${i ? void 0 : o ?? g} kind=neutral .label=${a} @click=${this._locate} title=${a ?? Q}>${i ? m`<calcite-loader inline label></calcite-loader>` : null}</calcite-button>` || ""}${h ? m`<calcite-tooltip open overlay-positioning=fixed .referenceElement=${this.el}>${h}</calcite-tooltip>` : null}</div>`;
  }
}
I("geoscene-locate", Ee);
export {
  Ee as GeosceneLocate
};