lib/excalt/helpers/todo_formatter.ex

defmodule Excalt.Helpers.TodoFormatter do
  @moduledoc """
  Helpers to format a list of todos as returned and parsed by Excalt.Todo.
  """

  @doc """
  Formats the list of todos into human-readable format.
  The input is a list of todos as returned from Excalt.Todo.parsed_list!/4.
  If exclude_completed is true, only the not yet completed todos are being shown.
  """
  @spec formatted_txt(
          todos :: [Excalt.Todo.t()],
          exclude_completed :: Boolean.t()
        ) :: String.t()
  def formatted_txt(todos, exclude_completed \\ false) do
    todos =
      if exclude_completed do
        Enum.filter(todos, fn t ->
          todo = List.first(t.icalendar.todos)
          is_nil(todo.completed)
        end)
      else
        todos
      end

    "Todos\n" <>
      Enum.reduce(todos, "", fn event, acc ->
        todo = List.first(event.icalendar.todos)

        acc <>
          Timex.format!(todo.due, "%d-%b-%Y %H:%M", :strftime) <>
          " #{todo.summary} (#{todo.description})\n"
      end)
  end
end