defmodule Outlook.Public.Artikel do
  use Ecto.Schema

  alias Outlook.Public.Artikel

  embedded_schema do
    field :title, :string
    field :date, :utc_datetime
    field :public_content, :string
    field :title_org, :string
    field :url_org, :string
    field :date_org, :utc_datetime
    field :autor_name, :string
    field :author_id, :integer
    field :teaser, :string
    # field :autor, Autor
  end

  def translate_unicode(str) do
    mapping = %{"Ä" => "Ae",
                "Ö" => "Oe",
                "Ü" => "Ue",
                "ä" => "ae",
                "ö" => "oe",
                "ü" => "ue",
                "ß" => "ss"}
    {:ok, re} = "[#{Map.keys(mapping) |> Enum.join}]" |> Regex.compile("u")
    Regex.replace(re, str, fn(c) -> mapping[c] end)
  end

  def spit_title(title) do
    title
    |> translate_unicode()
    |> String.replace(~r/[^\w\s-]/u, "")
    |> String.replace(~r/(\s|-)+/u, "-")
  end

  defimpl Phoenix.Param, for: Artikel do
    def to_param(%{id: id, title: title}) do
      "#{Artikel.spit_title(title)}--#{Integer.to_string(id, 36) |> String.downcase()}"
    end
  end
end
