defmodule ZoeyscomputerWeb.GistLive.Index do
  use ZoeyscomputerWeb, :live_view

  alias Zoeyscomputer.Gists
  alias Zoeyscomputer.Gists.Gist

  @impl true
  def mount(_params, _session, socket) do
    socket = socket |> assign(:current_user, socket.assigns.current_user)

    if connected?(socket) && socket.assigns.current_user do
      {:ok, stream(socket, :gists, Gists.list_gists())}
    else
      {:ok, stream(socket, :gists, [])}
    end
  end

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

  defp apply_action(socket, :edit, %{"id" => id}) do
    socket
    |> assign(:page_title, "Edit Gist")
    |> assign(:current_user, socket.assigns.current_user)
    |> assign(:gist, Gists.get_gist!(id))
  end

  defp apply_action(socket, :new, _params) do
    socket
    |> assign(:page_title, "New Gist")
    |> assign(:current_user, socket.assigns.current_user)
    |> assign(:gist, %Gist{
      code: "",
      lang: nil
    })
  end

  defp apply_action(socket, :show, %{"id" => id}) do
    socket
    |> assign(:page_title, "Show Gist")
    |> assign(:gist, Gists.get_gist!(id))
  end

  defp apply_action(socket, :index, _params) do
    socket
    |> assign(:page_title, "Listing Gists")
    |> assign(:gist, nil)
  end

  # Catch-all clause for when live_action is nil
  defp apply_action(socket, nil, _params) do
    socket
    |> assign(:page_title, "Listing Gists")
    |> assign(:gist, nil)
  end

  @impl true
  def handle_info({ZoeyscomputerWeb.GistLive.FormComponent, {:saved, gist}}, socket) do
    {:noreply, stream_insert(socket, :gists, gist)}
  end

  @impl true
  def handle_event("delete", %{"id" => id}, socket) do
    gist = Gists.get_gist!(id)
    {:ok, _} = Gists.delete_gist(gist)

    {:noreply, stream_delete(socket, :gists, gist)}
  end
end
