import axios from "axios";

const API_KEY = "AIzaSyAu4aqv3DMtmugZo1wJzfcwQlM4Od6pZi0";

const MAPS_BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json";

const coords = async () => {
    return new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition((position) => {
            resolve({
                lat: position.coords.latitude,
                lng: position.coords.longitude,
            });
        }, reject);
    });
};

export const currentLocation = async () => {
    const { lat, lng } = await coords();
    const data = await fetch(
        `${MAPS_BASE_URL}?latlng=${lat},${lng}&key=${API_KEY}`,
        {
            method: "GET",
        }
    );
    const json = await data.json();

    const addressIndex =
        json.results.length - 2 > 0 ? json.results.length - 2 : 0;
    const address = json.results[addressIndex].formatted_address;

    return { address, lat, lng };
};

export const addressFromLngLat = async (lat, lng) => {
    const data = await fetch(
        `${MAPS_BASE_URL}?latlng=${lat},${lng}&key=${API_KEY}`,
        {
            method: "GET",
        }
    );
    const json = await data.json();

    const addressIndex =
        json.results.length - 2 > 0 ? json.results.length - 2 : 0;
    const address = json.results[addressIndex].formatted_address;

    return { address, lat, lng };
};

const rad = function (x) {
    return (x * Math.PI) / 180;
};

export const getDistance = function (p1, p2) {
    var R = 6378137; // Earth’s mean radius in meter
    var dLat = rad(p2.lat() - p1.lat);
    var dLong = rad(p2.lng() - p1.lng);
    var a =
        Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(rad(p1.lat)) *
            Math.cos(rad(p2.lat())) *
            Math.sin(dLong / 2) *
            Math.sin(dLong / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    return d; // returns the distance in KM * by 1.5 to approx fix the distance scaling
};
