defmodule Outlook.Autoren do
  @moduledoc """
  The Autoren context.
  """

  import Ecto.Query, warn: false
  alias Outlook.Repo

  alias Outlook.Articles.Article
  alias Outlook.Translations.Translation

  alias Outlook.Authors.Author

  def list_autoren do
    Repo.all(Author)
  end

  def get_autor!(id) do
    Repo.get!(Author, id)
    |> Repo.preload([articles: [:translations]])
  end

  @doc "This is ugly"
  def list_artikel(author) when is_struct(author), do: list_artikel(author.id)
  def list_artikel(author_id) do
    aids = Repo.all(from a in Article,
      select: [:id],
      where: a.author_id == ^author_id)
    |> Enum.map(fn a -> a.id end)
    Repo.all(from t in Translation,
      select: [t.title, t.teaser, t.date, t.user_id],
      where: t.article_id in ^aids and t.public == true)
  end
end
