Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Evaluate Open Trip Planner

evaluate-open-trip-planner.livemd

Evaluate Open Trip Planner

Section

defmodule EvaluateOpenTripPlanner.Helpers do
  @moduledoc false

  def attach_itineraries_to_plan(%{"from" => from, "to" => to} = plan, datetime) do
    itineraries =
      plan(from, to, depart_at: datetime)
      |> Kernel.elem(1)
      |> itineraries_to_strings()

    plan
    |> Map.put("datetime", Timex.format!(datetime, "%FT%H:%M", :strftime))
    |> Map.put("itineraries", itineraries)
  end

  defp address_to_named_position(address) do
    address
    |> LocationService.geocode()
    |> Kernel.elem(1)
    |> List.first()
    |> TripPlan.NamedPosition.new()
  end

  defp itineraries_to_strings(itineraries) when is_binary(itineraries) do
    [itineraries]
  end

  defp itineraries_to_strings(itineraries) when is_list(itineraries) do
    Enum.map(itineraries, &itinerary_to_string/1)
  end

  defp itinerary_to_string(itinerary) do
    Enum.map(itinerary.legs, &leg_to_string/1)
  end

  defp leg_to_string(%{description: "WALK"} = leg) do
    "#{leg.description} FROM #{leg.from.name} TO #{leg.to.name}"
  end

  defp leg_to_string(%{description: "BUS"} = leg) do
    "TAKE #{leg.name} #{leg.description} FROM #{leg.from.name} TO #{leg.to.name}"
  end

  defp leg_to_string(leg) do
    "TAKE #{leg.long_name} #{leg.description} FROM #{leg.from.name} TO #{leg.to.name}"
  end

  defp plan(from, to, opts) do
    TripPlan.Api.OpenTripPlanner.plan(
      address_to_named_position(from),
      address_to_named_position(to),
      opts
    )
  end
end

alias EvaluateOpenTripPlanner.Helpers
Application.start(:yamerl)

write_path =
  System.tmp_dir!()
  |> Path.join("itineraries.yml")
  |> IO.inspect()

datetimes =
  File.cwd!()
  |> Path.join("/livebooks/datetimes.yml")
  |> YamlElixir.read_from_file!()
  |> Enum.map(fn datetime ->
    datetime
    |> Timex.parse!("%Y-%m-%dT%H:%M", :strftime)
    |> Timex.to_datetime("America/New_York")
  end)

plans =
  File.cwd!()
  |> Path.join("/livebooks/plans.yml")
  |> YamlElixir.read_from_file!()
  |> Enum.map(fn plan ->
    Enum.map(datetimes, fn datetime ->
      Helpers.attach_itineraries_to_plan(plan, datetime)
    end)
  end)
  |> List.flatten()

yaml = Ymlr.document!(plans)

File.write!(write_path, yaml)