const RADIUS = 2000.0;
const MAX_RESULTS = 20;
const INCLUDED_TYPES = ["park"];

let map: google.maps.Map;
let pos: google.maps.LatLngLiteral = {lat: 30, lng: -110};

async function initMap() {
  const { Map } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;

  map = new Map(document.getElementById("map") as HTMLElement, {
    center: pos,
    zoom: 8,
    mapId: "DEMO_MAP",
  });
}

async function find_places(position: google.maps.LatLngLiteral) {
  // @ts-ignore
  const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;
  const { InfoWindow } = await google.maps.importLibrary("maps") as google.maps.MapsLibrary;

  let response = await fetch("https://places.googleapis.com/v1/places:searchNearby", {
    method: "POST",
    headers: new Headers({
      "Content-Type": "application/json",
      "X-Goog-Api-Key": "AIzaSyCneCqjzobnZ-ksYh85eosk1whovucTjQE",
      "X-Goog-FieldMask": "places.location,places.displayName",
    }),
    body: JSON.stringify({
      includedTypes: INCLUDED_TYPES,
      maxResultCount: MAX_RESULTS.toString(),
      locationRestriction: {
        circle: {
          center: {
            latitude: position.lat,
            longitude: position.lng,
          },
          radius: RADIUS.toString(),
        },
      },
    })
  });
  let locations: {places: [{location: {latitude: number, longitude: number}, displayName: {text: string}}]} = await response.json();

  const infoWindow = new google.maps.InfoWindow({
    content: "",
    disableAutoPan: true,
  });

  console.log(locations);

  const labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  let markers = locations["places"].map((element, i) => {
    let place = element["location"];
    let latitude = place["latitude"];
    let longitude = place["longitude"];
      
    let label = labels[i % labels.length];
    const pinGlyph = new google.maps.marker.PinElement({
      glyph: label,
      glyphColor: "white"
    });
    const marker = new google.maps.marker.AdvancedMarkerElement({
      position: {
        lat: latitude,
        lng: longitude,
      },
      content: pinGlyph.element,
    });

    marker.addListener("click", () => {
      infoWindow.setContent(position.lat + ", " + position.lng);
      infoWindow.open(map, marker);
    });
    return marker;
  });

  // @ts-ignore
  new markerClusterer.MarkerClusterer({ markers, map });
}

async function handle_geolocation() {
  const { AdvancedMarkerElement } = await google.maps.importLibrary("marker") as google.maps.MarkerLibrary;
  navigator.geolocation.getCurrentPosition(
    (position: GeolocationPosition) => {
      pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude,
      };
      map.setCenter(pos)
      map.setZoom(15);
      find_places(pos);
      new AdvancedMarkerElement({
        map: map,
        position: pos,
        title: "You",
      })
    }
  );
}

initMap().then(() => {
  if (navigator.geolocation) {
    handle_geolocation();
  }
});

