defmodule OutlookWeb.TranslationLive.NewEdit do
  use OutlookWeb, :live_view

  alias Outlook.{Articles,Translations}
  alias Outlook.Translations.{Translation,Basic}
  alias OutlookWeb.TranslationLive.FormComponent

  @form_cmpnt_id "formkomponente"

  @impl true
  def render(assigns) do
    ~H"""
    <.live_component
      module={FormComponent}
      id={@form_cmpnt_id}
      title={@page_title}
      action={@live_action}
      translation={@translation}
      translation_content={@translation_content}
      current_user={@current_user}
      navigate={~p"/articles/#{@translation.article}"}
    />
    """
  end

  @impl true
  def handle_params(%{"article_id" => article_id} = _params, _session, socket) when socket.assigns.live_action == :new do
    socket = socket
      |> assign_new(:translation, fn ->
        %Translation{
          article_id: article_id,
          article: get_article(article_id)
        }
        end)
      |> common_assigns()
    {:noreply, assign_new(socket, :translation_content, fn ->
        Basic.internal_tree_to_tunit_map(socket.assigns.translation.article.content) end)}
  end

  def handle_params(%{"id" => id} = _params, _session, socket) when socket.assigns.live_action == :edit do
    socket = socket
      |> assign(:translation, Translations.get_translation!(id))
      |> common_assigns()
    {:noreply, assign(socket, :translation_content, socket.assigns.translation.content)}
  end

  defp get_article(article_id) do
    Articles.get_article!(article_id)
  end

  defp common_assigns(socket) do
    assign(socket, form_cmpnt_id: @form_cmpnt_id)
    |> assign(:page_title, page_title(socket.assigns.live_action))
  end

  @impl true
  def handle_info({:progress, payload}, socket) do
    send_update(self(), FormComponent, progress: payload.progress, id: @form_cmpnt_id)
    {:noreply, socket}
  end

  def handle_info({:translation, payload}, socket) do
    send_update(self(), FormComponent, deepl_translation: payload, id: @form_cmpnt_id)
    {:noreply, socket}
  end

  defp page_title(:new), do: "New Translation"
  defp page_title(:edit), do: "Edit Translation"
end
