defmodule Outlook.Translations.Translation do
  use Ecto.Schema
  import Ecto.Changeset

  alias Outlook.Accounts.User
  alias Outlook.Articles.Article
  alias Outlook.Translations.{TranslationUnitsMap,Translation}

  schema "translations" do
    field :content, TranslationUnitsMap
    field :date, :utc_datetime
    field :language, :string, default: "DE"
    field :public, :boolean, default: false
    field :teaser, :string
    field :public_content, :string
    field :title, :string
    field :unauthorized, :boolean, default: false
    belongs_to :user, User
    belongs_to :article, Article

    timestamps()
  end

  @doc false
  def changeset(translation, attrs) do
    translation
    |> cast(attrs, [:language, :title, :teaser, :date, :public, :unauthorized, :article_id, :public_content])
    |> cast(attrs, [:content])
    |> validate_required([:language, :title, :content, :date, :public, :unauthorized, :article_id])
    |> unique_constraint([:language, :article_id],
        message: "translation for this language already exists",
        name: :article_id_lang_unique_index)
    |> foreign_key_constraint(:article_id)
  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/[^-0-9A-Za-z ]/u, "_")
    |> String.replace(~r/[^\w\s-]/u, "")
    |> String.replace(~r/(\s|-)+/u, "-")
  end

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