defmodule DiskuyWeb.ThreadController do
  use DiskuyWeb, :controller

  alias Diskuy.Forum
  alias Diskuy.Forum.Thread
  alias Diskuy.Likes
  alias Diskuy.Likes.ThreadLike
  alias DiskuyWeb.Auth.Guardian

  action_fallback DiskuyWeb.FallbackController

  def index(conn, _params) do
    threads = Forum.list_threads()
    render(conn, "index.json", threads: threads)
  end

  def create(conn, %{"thread" => thread_params}) do
    new_params = put_user_id(conn, %{"thread" => thread_params})
    with {:ok, %Thread{} = thread} <- Forum.create_thread(new_params) do
      conn
      |> put_status(:created)
      |> put_resp_header("location", Routes.thread_path(conn, :show, thread))
      |> render("show.json", thread: thread)
    end
  end

  def show(conn, %{"id" => id}) do
    thread = Forum.get_thread!(id)
    render(conn, "show.json", thread: thread)
  end

  def update(conn, %{"id" => id, "thread" => thread_params}) do
    thread = Forum.get_thread!(id)
    with {:ok, %Thread{} = thread} <- Forum.update_thread(thread, thread_params) do
      render(conn, "show.json", thread: thread)
    end
  end

  def delete(conn, %{"id" => id}) do
    thread = Forum.get_thread!(id)
    with {:ok, %Thread{}} <- Forum.delete_thread(thread) do
      send_resp(conn, :no_content, "")
    end
  end

  def add_like(conn, %{"id" => id}) do
    current_user = Guardian.Plug.current_resource(conn)
    thread = Forum.get_thread!(id)

    with {:ok, %ThreadLike{} = _thread_like} <- Likes.create_thread_like(%{"user_id" => current_user.id,
                                                                           "thread_id" => id}),
         {:ok, %Thread{} = thread} <- Forum.update_thread(thread, %{"points" => (thread.points+ 1)}) do
         render(conn, "show.json", thread: thread)
    end
  end

  def delete_like(conn, %{"id" => id}) do
    current_user = Guardian.Plug.current_resource(conn)
    thread = Forum.get_thread!(id)
    thread_like = Likes.get_thread_like_by_refer!(current_user.id, id)

    with {:ok, %ThreadLike{}} <- Likes.delete_thread_like(thread_like),
         {:ok, %Thread{} = thread} <- Forum.update_thread(thread, %{"points" => (thread.points-1)}) do
         render(conn, "show.json", thread: thread)
    end
  end

  defp put_user_id(conn, %{"thread" => thread_params}) do
    current_user = Guardian.Plug.current_resource(conn)
    new_params = Map.put(thread_params, "user_id", current_user.id)
    new_params
  end
end