/* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
import R from "@arcgis/core/core/Accessor.js";
import { property as l, subclass as U } from "@arcgis/core/core/accessorSupport/decorators.js";
import p from "@arcgis/core/core/Error.js";
import { watch as O } from "@arcgis/core/core/reactiveUtils.js";
import h from "@arcgis/core/Graphic.js";
import x from "@arcgis/core/symbols/CIMSymbol.js";
import { t as T, i as G } from "./async-utils.js";
import N from "@arcgis/core/geometry/Point.js";
import * as d from "@arcgis/core/geometry/operators/projectOperator.js";
import g from "@arcgis/core/config.js";
import { geographicToWebMercator as I } from "@arcgis/core/geometry/support/webMercatorUtils.js";
import L from "@arcgis/core/portal/Portal.js";
import { project as D } from "@arcgis/core/rest/geometryService.js";
import F from "@arcgis/core/rest/support/ProjectParameters.js";
import { log as y } from "@arcgis/toolkit/log";
let m = !1;
const j = {
  maximumAge: 0,
  timeout: 15e3,
  enableHighAccuracy: !0
};
function z(e) {
  const t = "geolocation" in navigator;
  return t || y("warn", e, "Geolocation is not supported by this browser."), t;
}
function Q(e) {
  const t = window.isSecureContext;
  return t || m || (m = !0, y("warn", e, "Geolocation requires a secure origin.")), t;
}
function k(e) {
  return z(e) && Q(e);
}
function ge(e) {
  return e ??= j, new Promise((o, r) => {
    setTimeout(
      () => r(new p("geolocation:timeout", "getting the current geolocation position timed out")),
      e?.timeout ?? 15e3
    ), navigator.geolocation.getCurrentPosition(o, r, e ?? void 0);
  });
}
function K(e, t) {
  const { position: o, view: r } = e, n = H(o)?.coords;
  if (!n)
    throw new p("geometry-service:no-coords", "Geolocation has no coordinates");
  const a = J(n);
  return V(a, r, t);
}
function H(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 J({ longitude: e, latitude: t, altitude: o }) {
  return new N({
    longitude: e,
    latitude: t,
    z: o || void 0,
    spatialReference: {
      wkid: 4326
    }
  });
}
async function V(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(I(e)) : d.isLoaded() ? await Promise.resolve(d.execute(e, r)) : await q(o).then(async (i) => {
    if (!i)
      throw new p("geometry-service:missing-url", "Geometry service URL is missing");
    const n = new F({
      geometries: [e],
      outSpatialReference: r
    });
    return (await D(i, n, o))[0];
  });
}
async function q(e) {
  if (g.geometryServiceUrl)
    return await Promise.resolve(g.geometryServiceUrl);
  const t = L.getDefault();
  try {
    await t.load(e);
  } catch {
  }
  return t.helperServices?.geometry?.url;
}
var W = Object.defineProperty, X = Object.getOwnPropertyDescriptor, c = (e, t, o, r) => {
  for (var i = r > 1 ? void 0 : r ? X(t, o) : t, n = e.length - 1, a; n >= 0; n--)
    (a = e[n]) && (i = (r ? a(t, o, i) : a(i)) || i);
  return r && i && W(t, o, i), i;
};
const B = 2500;
function f(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 A = {
  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/zM7wdw725rUY78DBXtmATA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Lj5KUzFzOMTni4btxoUzXPzIIOwLnEPxGVqlyWoTdO/WNRUXJhDmAgNAJVd0eABj8FTCvLbpEnxdOycJlFNXVq6MDvzthwOQ654LaMGGVofQWIWtXhM9xaCQp85QIZFMPXcpuUPH3uquJj6htVonvySD+KY6c2AulPAzHdVaZElvPCGBgvkIRUECr1J4qmV6LdGyJvAnu+94HZMla1Eg1AuGVyQWnNCwzqsUXK5+AIsUyPRc1Rbpi93X1xK9tsXtkj9U7INWSWvU0DaZ6OlVAmUDiqgbrwY2Z3ThRVKFXrgi/R0x9GMplxAyER6ynAtZin1DQoLVznLMU+/mywMf3dlDpbyMlbjLQDhLw/Sh24sm5dhTrlHKgS/T0X2zLw/sLeGr5OlEbg2uHwAFw5reKuKsJj8kcIj0zq9H5PqAj+z6E8y+YRIaUhnAEOrcWgv9m3shQ1H7mz5duVJtDLhZqZcNlrEDwXKwCzncdFg+PJeVf1m3uPUupLR7Hq6tHNyLhw1TCmdGbm0BmaUjr63LzaMBH943D9f+yO5uZ7HfcLktqdwqMU0jtPUDN6vDOfzgKFrXtta6q83vfHU4M5KoURbT4W3zsPIqrgQFO8GozV8ocZGOTN4dRdRowN6CnOLmKkk5t7H1i+HPNGJj2kj7buYajoRXh2+36eOt+2nENrrF3ozODEmFC0D4hjbQNgYc+DSYjd9qqGSJXqL/tZ16/DWdfvw9bbCt41hcpYn9RAEX9Q22fwC74ny5v9iplQAAAABJRU5ErkJggg=="
}, Z = f("layer"), Y = f("background"), _ = new x({
  data: {
    type: "CIMSymbolReference",
    symbol: {
      type: "CIMPointSymbol",
      symbolLayers: [Z, Y, A],
      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 s = class extends R {
  constructor() {
    super(...arguments), this._geolocationUsable = !0, this.goToLocationEnabled = !0, this.graphic = new h({
      symbol: _
    }), this.rotationEnabled = !0;
  }
  //#region Lifecycle
  initialize() {
    k(this) || (this._geolocationUsable = !1), this.addHandles([
      O(
        () => 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() {
    A.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 : B;
    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 n = {
      target: e,
      scale: t
    };
    this.rotationEnabled && this._addHeading({
      heading: o,
      target: n,
      view: i
    });
    const a = { signal: r.signal };
    if (T(a), this.goToOverride && i)
      return await this.goToOverride(i, {
        target: n,
        options: a
      });
    await i.goTo(n, a);
  }
  async updatePosition(e, t) {
    try {
      const o = this.view, r = await K({ position: e, view: o }, { signal: t.signal }), { graphic: i } = this, { timestamp: n, coords: a } = e, { accuracy: w, altitude: v, altitudeAccuracy: b, latitude: P, longitude: S, speed: C } = a, u = this._getHeading(e, o), M = {
        timestamp: n,
        accuracy: w,
        altitude: v,
        altitudeAccuracy: b,
        heading: u,
        latitude: P,
        longitude: S,
        speed: C
      };
      i && (i.geometry = r, i.attributes = M);
      const E = this._getScale(o);
      await this._animatePoint(r, E, u, t);
    } catch (o) {
      if (!G(o))
        throw new p("geolocation-positioning:invalid-point", "Cannot position invalid point", {
          error: o
        });
    }
    return e;
  }
  //#endregion
};
c([
  l()
], s.prototype, "_geolocationUsable", 2);
c([
  l()
], s.prototype, "geolocationOptions", 2);
c([
  l()
], s.prototype, "goToLocationEnabled", 2);
c([
  l()
], s.prototype, "goToOverride", 2);
c([
  l({
    type: h
  })
], s.prototype, "graphic", 2);
c([
  l()
], s.prototype, "scale", 2);
c([
  l()
], s.prototype, "rotationEnabled", 2);
c([
  l()
], s.prototype, "view", 2);
s = c([
  U("map-components.geolocation.GeolocationPositioning")
], s);
const me = s;
export {
  me as G,
  ge as g
};
