defmodule MemexWeb.PipelineLive.Index do
  use MemexWeb, :live_view
  alias Memex.{Pipelines, Pipelines.Pipeline}

  @impl true
  def mount(%{"search" => search}, _session, socket) do
    {:ok, socket |> assign(:search, search) |> display_pipelines()}
  end

  def mount(_params, _session, socket) do
    {:ok, socket |> assign(:search, nil) |> display_pipelines()}
  end

  @impl true
  def handle_params(params, _url, %{assigns: %{live_action: live_action}} = socket) do
    {:noreply, apply_action(socket, live_action, params)}
  end

  defp apply_action(%{assigns: %{current_user: current_user}} = socket, :edit, %{"slug" => slug}) do
    %{slug: slug} = pipeline = Pipelines.get_pipeline_by_slug(slug, current_user)

    socket
    |> assign(
      page_title: gettext("edit %{slug}", slug: slug),
      pipeline: pipeline
    )
  end

  defp apply_action(%{assigns: %{current_user: %{id: current_user_id}}} = socket, :new, _params) do
    socket
    |> assign(
      page_title: gettext("new pipeline"),
      pipeline: %Pipeline{visibility: :private, user_id: current_user_id}
    )
  end

  defp apply_action(socket, :index, _params) do
    socket
    |> assign(
      page_title: gettext("pipelines"),
      pipeline: nil,
      search: nil
    )
    |> display_pipelines()
  end

  defp apply_action(socket, :search, %{"search" => search}) do
    socket
    |> assign(
      page_title: gettext("pipelines"),
      pipeline: nil,
      search: search
    )
    |> display_pipelines()
  end

  @impl true
  def handle_event("delete", %{"id" => id}, %{assigns: %{current_user: current_user}} = socket) do
    pipeline = Pipelines.get_pipeline!(id, current_user)
    {:ok, %{slug: slug}} = Pipelines.delete_pipeline(pipeline, current_user)

    socket =
      socket
      |> assign(:pipelines, Pipelines.list_pipelines(current_user))
      |> put_flash(:info, gettext("%{slug} deleted", slug: slug))

    {:noreply, socket}
  end

  def handle_event("search", %{"search" => %{"search_term" => ""}}, socket) do
    {:noreply, socket |> push_patch(to: ~p"/pipelines")}
  end

  def handle_event("search", %{"search" => %{"search_term" => search_term}}, socket) do
    {:noreply, socket |> push_patch(to: ~p"/pipelines/#{search_term}")}
  end

  defp display_pipelines(%{assigns: %{current_user: %{} = current_user, search: search}} = socket) do
    socket |> assign(:pipelines, Pipelines.list_pipelines(search, current_user))
  end

  defp display_pipelines(%{assigns: %{search: search}} = socket) do
    socket |> assign(:pipelines, Pipelines.list_public_pipelines(search))
  end
end
