defmodule Microwaveprop.Rover.DriveTime do
  @moduledoc """
  Distance, drive-time, and compass-bearing helpers for the rover
  planner. All inputs are degrees / kilometres; no I/O.
  """

  @earth_radius_km 6371.0
  @avg_speed_kmh 65.0

  @spec haversine_km({float(), float()}, {float(), float()}) :: float()
  def haversine_km({lat1, lon1}, {lat2, lon2}) do
    rlat1 = deg_to_rad(lat1)
    rlat2 = deg_to_rad(lat2)
    dlat = deg_to_rad(lat2 - lat1)
    dlon = deg_to_rad(lon2 - lon1)

    a =
      :math.sin(dlat / 2) ** 2 +
        :math.cos(rlat1) * :math.cos(rlat2) * :math.sin(dlon / 2) ** 2

    2 * @earth_radius_km * :math.asin(:math.sqrt(a))
  end

  @spec drive_min(float()) :: float()
  def drive_min(dist_km) when is_number(dist_km), do: dist_km / @avg_speed_kmh * 60.0

  @spec bearing_compass({float(), float()}, {float(), float()}) :: String.t()
  def bearing_compass(from, to) do
    from |> bearing_deg(to) |> compass_for()
  end

  @spec bearing_deg({float(), float()}, {float(), float()}) :: float()
  def bearing_deg({lat1, lon1}, {lat2, lon2}) do
    rlat1 = deg_to_rad(lat1)
    rlat2 = deg_to_rad(lat2)
    dlon = deg_to_rad(lon2 - lon1)

    y = :math.sin(dlon) * :math.cos(rlat2)
    x = :math.cos(rlat1) * :math.sin(rlat2) - :math.sin(rlat1) * :math.cos(rlat2) * :math.cos(dlon)

    y |> :math.atan2(x) |> rad_to_deg() |> normalize_deg()
  end

  @compass_points {"N", "NE", "E", "SE", "S", "SW", "W", "NW"}

  defp compass_for(bearing) do
    index = bearing |> Kernel.+(22.5) |> div_floor(45.0) |> rem(8)
    elem(@compass_points, index)
  end

  defp div_floor(a, b), do: trunc(a / b)

  defp deg_to_rad(deg), do: deg * :math.pi() / 180.0
  defp rad_to_deg(rad), do: rad * 180.0 / :math.pi()
  defp normalize_deg(deg), do: deg |> Kernel.+(360.0) |> :math.fmod(360.0)
end
