summaryrefslogtreecommitdiff
path: root/lib/aggiedit_web/live/post_live/index.ex
blob: 26c078c555d303e959eac1806bca48e48ac37838 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
defmodule AggieditWeb.PostLive.Index do
  use AggieditWeb, :live_view

  alias Aggiedit.Accounts.User
  alias Aggiedit.Roles
  alias Aggiedit.Rooms
  alias Aggiedit.Rooms.{Post, Room}
  alias Aggiedit.Repo

  @impl true
  def mount(%{"room_id" => room_id} = params, session, socket) do
    {:ok, socket} = AggieditWeb.PostLive.Helper.assign_socket_room_and_user_or_error(params, session, socket)
#    if !is_nil(socket.assigns[:room]) do
#      {:ok, assign(socket, %{:posts => socket.assigns.room |> Repo.preload(:posts) |> Map.get(:posts)})}
#    else 
#      {:ok, socket}
#    end
    case socket.assigns do
      %{:room => room} -> 
        {:ok, assign(socket, %{:posts => room |> Repo.preload(:posts) |> Map.get(:posts)})}
      _ -> {:ok, socket}
    end
  end

  @impl true
  def handle_params(%{"id" => id}=params, _url, socket) do
    post = Rooms.get_post!(id)
    if Roles.guard?(socket.assigns.current_user, socket.assigns.live_action, post) do
      {:noreply, apply_action(socket, socket.assigns.live_action, params)}
    else
      {:noreply, socket |> put_flash(:error, "You do not have permission to edit this post.") |> redirect(to: Routes.post_index_path(socket, :index, socket.assigns.room))}
    end
  end

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

  defp apply_action(socket, :edit, %{"id" => id}=params) do
    socket
    |> assign(:page_title, "Edit Post")
    |> assign(:post, Rooms.get_post!(id) |> Repo.preload(:upload))
  end

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

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

  @impl true
  def handle_event("delete", %{"id" => id}, socket) do
    post = Rooms.get_post!(id)
    if Roles.guard?(socket.assigns.current_user, :delete, post) do
      Rooms.delete_post(post)
      {:noreply, socket |> put_flash(:success, "Post deleted.") |> redirect(to: Routes.post_index_path(socket, :index, socket.assigns.room))}
    else
      {:noreply, socket |> put_flash(:error, "You do not have permission to delete this post.") |> redirect(to: Routes.post_index_path(socket, :index, socket.assigns.room))}
    end
  end
end