defmodule CakeWeb.LayoutLive.Index do
  use CakeWeb, :live_view

  alias Cake.Layouts
  alias Cake.Layouts.Layout

  @impl true
  def mount(_params, _session, socket) do
    {:ok, assign(socket, :layouts, list_layouts())}
  end

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

  defp apply_action(socket, :edit, %{"id" => id}) do
    socket
    |> assign(:page_title, "Edit Layout")
    |> assign(:layout, Layouts.get_layout!(id))
  end

  defp apply_action(socket, :new, _params) do
    socket
    |> assign(:page_title, "New Layout")
    |> assign(:layout, %Layout{})
  end

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

  @impl true
  def handle_event("delete", %{"id" => id}, socket) do
    layout = Layouts.get_layout!(id)
    {:ok, _} = Layouts.delete_layout(layout)

    {:noreply, assign(socket, :layouts, list_layouts())}
  end

  defp list_layouts do
    Layouts.list_layouts()
  end
end