package com.isidroid.location.ext

import androidx.compose.ui.text.intl.Locale
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin
import kotlin.math.sqrt

internal fun calculateDistanceBetweenPoints(
    locale: Locale,
    myLat: Double,
    myLng: Double,
    locationLat: Double,
    locationLng: Double
): Double {
    val earthRadius = 6371.0 // Радиус Земли в километрах

    val dLat = Math.toRadians(locationLat - myLat)
    val dLng = Math.toRadians(locationLng - myLng)
    val a = sin(dLat / 2) * sin(dLat / 2) +
            cos(Math.toRadians(myLat)) * cos(Math.toRadians(locationLat)) *
            sin(dLng / 2) * sin(dLng / 2)
    val c = 2 * atan2(sqrt(a), sqrt(1 - a))

    val distanceKm = earthRadius * c

    val distance = if (locale.isMileUnit)
        convertKmToMiles(distanceKm)
    else
        distanceKm

    return distance
}

val Locale.isMileUnit get() = region in arrayOf("US")

internal fun convertKmToMiles(km: Double): Double {
    return km * 0.621371
}
