import { YMapsApi } from "@pbe/react-yandex-maps/typings/util/typing";

import { Address, Location, StringLocation } from "../types";
import { splitLocation, stringifyLocation } from "../helper";

export const formatLocation = (location: Location | undefined): StringLocation | '' => {
  if (!location) {
    return '';
  }
  return stringifyLocation(location);
};

const coordinatesRe = new RegExp(/^[-0-9]+.[0-9]+,[-0-9]+.[0-9]+/);
export const extractAddress = (value: string) => value.replace(coordinatesRe, '').trim();

export const getLocationByAddress = async (ymaps: YMapsApi, address: Address): Promise<Location> => {
  try {
    const result = await ymaps.geocode(address);
    const firstGeoObject = result.geoObjects.get(
      0,
    ) as unknown as ymaps.IGeoObject<ymaps.IBasePointGeometry>;
    const [latitude, longitude] = firstGeoObject.geometry.getCoordinates();
    return { coordinates: [latitude, longitude], address };    
  } catch (error) {
    console.error(error);    
  }
};

export const isRealLocation = async (ymaps: YMapsApi, stringifiedLocation: StringLocation) => {
  const [coordinates, address] = splitLocation(stringifiedLocation);
  try {
    const result = await ymaps.geocode(coordinates);
    const firstGeoObject = result.geoObjects.get(0) as ymaps.GeocodeResult;
    const addressByCoordinates = firstGeoObject.getAddressLine();
  
    return address === addressByCoordinates;
  } catch (error) {
    console.error(error);
  }
};