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

  alias Outlook.Translations.Translation
  alias Outlook.Articles.Article
  alias Outlook.Authors.Author

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

  def list_artikel do
    Repo.all(from t in Translation, where: t.public == true)
    |> Repo.preload([article: :author])
  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: [
        title: t.title,
        date: t.date,
        public_content: t.public_content,
        title_org: a.title,
        url_org: a.url,
        date_org: a.date,
        author: au.name,
        author_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 |> Enum.into(%{})}
    end
  end

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