defmodule Outlook.Public do
@moduledoc """
This should replace Outlook.Artikel and Outlook.Autoren for
both of which embedded schemas should be created, for Artikel the schema should
implement to_param protocol (no more needed for Outlook.Translations.Translation then).
"""

  alias Outlook.Translations.Translation
  alias Outlook.Articles.Article
  alias Outlook.Authors.Author
  alias Outlook.Public.{Artikel,Autor}

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

  def list_artikel(language \\ "DE") do
    q = from t in Translation,
      join: a in Article, on: t.article_id == a.id,
      join: au in Author, on: a.author_id == au.id,
      select: %Artikel{
        title: t.title,
        date: t.date,
        teaser: t.teaser,
        id: t.id,
        date_org: a.date,
        autor_name: au.name,
      },
      where: t.public == true and t.language == ^language,
      order_by: [desc: t.date]
    Repo.all(q)
  end

  def get_artikel!(artikel) when is_struct(artikel), do: get_artikel!(artikel.id)
  def get_artikel!(id) do
    q = from t in Translation,
      join: a in Article, on: t.article_id == a.id,
      join: au in Author, on: a.author_id == au.id,
      select: %Artikel{
        title: t.title,
        date: t.date,
        public_content: t.public_content,
        title_org: a.title,
        url_org: a.url,
        date_org: a.date,
        autor_name: au.name,
        autor_id: au.id
      },
      where: t.id == ^id and t.public == true
    case Repo.one(q) do
      nil     -> {:error, "Artikel does not exist, or isn't public."}
      artikel -> {:ok, artikel}
    end
  end

  def get_artikel_by_tid(tid) do
    tid
    |> String.split(~r/--(?=[0-9A-Za-z])/)
    |> List.last()
    |> String.to_integer(36)
    |> get_artikel!()
  end

  # for /autoren/

  def list_autoren do
    Repo.all(Author)
  end

  def get_autor!(id) do
    q = from au in Author,
      select: %Autor{
        name: au.name,
        description: au.description,
        homepage_name: au.homepage_name,
        homepage_url: au.homepage_url,
      },
      where: au.id == ^id
    autor = Repo.one(q)

    q2 = from a in Article,
      join: t in Translation, on: t.article_id == a.id,
      select: %Artikel{
        title: t.title,
        date: t.date,
        teaser: t.teaser,
        id: t.id,
        date_org: a.date
      },
      where: a.author_id == ^id and t.public == true
    artikel = Repo.all(q2)

    %Autor{autor | artikel: artikel}
  end
end
