defmodule Outlook.InternalTree do

  alias Outlook.InternalTree.{Html,Modifiers,RawInternalBasic,InternalTree,Translation}
  alias Outlook.HtmlPreparations.HtmlPreparation
  alias Outlook.{Hyphenation, Translations}

  def render_html(tree) do
    tree
    |> HtmlPreparation.strip_whitespace_textnodes()
    |> Html.to_html()
  end

  def render_html_preview(tree, target \\ "1") do
    tree
    |> Html.to_html_preview(target)
  end

  require Logger
  def apply_modifier(tree, modifier, nids, opts \\ %{}) do
    # Logger.info modifier
    Modifiers.traverse_tree(tree, modifier, nids, opts)
  end

  def partition_text(tree) do
    # validate_sibling_collocation(tree)
    tree
    |> RawInternalBasic.set_split_markers()
    |> RawInternalBasic.partition_to_tunits()
  end

  def add_phx_click_event(tree, opts) do
    phx_opts = %{
      "phx-click": Keyword.get(opts, :click),
      "phx-target": Keyword.get(opts, :target) |> to_string,
      "phx-value-nid": fn n -> n.nid end
    }
    options = Map.put(%{}, Keyword.get(opts, :nodes, :elements), phx_opts)
    garnish(tree, options)
  end

  def garnish(tree, options) do
    options = Enum.reduce(
      ~w(el_ids el_names tu_ids)a,
      options,
      fn prop, opts -> Map.put_new(opts, prop, []) end
      )
    options = Enum.reduce(
      ~w(elements tunits)a,
      options,
      fn prop, opts -> Map.put_new(opts, prop, %{}) end
      )
    InternalTree.garnish(tree, options)
  end

  def render_translation(tree, translation) do
    Translation.render_translation(tree, translation)
  end

  def render_public_content(tree, translation, language) do
    Translation.render_translation(tree, translation)
    |> Html.render_doc()
    |> Hyphenation.hyphenate(language)
  end

  def legacy_export(translation_id) do
    translation = Translations.get_translation!(translation_id)
    content= Translation.render_translation(translation.article.content, translation.content)
    |> garnish(%{tunits: %{class: "ttrans", "data-ttrans-status": fn n -> Map.get(n, :status) end}})
    |> Html.render_doc
    |> Hyphenation.hyphenate(translation.language)
    IO.puts "writing export.html to #{File.cwd!}"
    File.write("export.html", content)
  end

  def get_tunit_ids(tree) do
    InternalTree.collect_tunit_ids(tree)
    # |> List.flatten()
  end
end
