defmodule Outlook.Translations.TranslationUnitsMap do
  use Ecto.Type

  alias Outlook.InternalTree.TranslationUnit

  def type, do: :map

  def cast(tumap) when is_map(tumap) do
    {:ok, tumap}
  end

  def cast(_), do: :error

  def load(serialized_map) when is_map(serialized_map) do
    tumap = for {key, val_str} <- serialized_map do
      val_map = Jason.decode!(val_str, keys: :atoms)
      val_tu = struct(TranslationUnit, %{val_map | status: String.to_atom(val_map.status)})
      {key, val_tu}
    end
    |> Enum.into(%{})
    {:ok, tumap}
  end

  def dump(tumap) when is_map(tumap) do
    serialized_map = for {key, val} <- tumap do
      {key, Jason.encode!(val |> Map.put(:eph, %{}))}
    end
    |> Enum.into(%{})
   {:ok, serialized_map}
  end

  def dump(_), do: :error
end
