defmodule BwcWeb.SessionController do
  use BwcWeb, :controller

  def update(conn, params) do
    cards = Bwc.list_cards()
    player = Map.get(params, "player")
    new_username = Map.get(player, "username")
    old_username = Map.get(player, "old_username")
    case {old_username, new_username} |> Bwc.change_name() do
      {:ok, player} ->
        conn
        |> put_session(:username, player.username)
        |> put_flash(:info, "You are now known as '#{player.username}'.")
        |>  redirect(to: Routes.card_path(conn, :index, cards))
      {:error, player} ->
        conn |> render("new.html", player: player, method: :update)
    end
  end

  def new(conn, _params) do
    player = Bwc.new_player()
    method = cond do
      conn |> get_session(:username) == "Nobody" ->
        :create
      true ->
        :update
    end
    render(conn, "new.html", player: player, method: method)
  end

  def set_name(conn, params) do
    import Logger
    new_username = Map.get(params, "username")
    old_username = Map.get(params, "old_username")
    case {old_username, new_username} |> Bwc.change_name() do
      {:ok, player} ->
        conn |> put_session(:username, player.username) |> render("set_name.json", username: player.username)

      {:error, username} ->
        conn |> render("error.json", username: username)
    end
  end

  def create(conn, %{"player" => %{"username" => username, "picture" => picture}}) do
    cards = Bwc.list_cards()

    case Bwc.get_or_create_player(username) do
      {:ok, player} ->
        conn
        |> put_session(:username, username)
        |> put_flash(:info, "Welcome to the game, #{player.username}.")
        |> redirect(to: Routes.card_path(conn, :index, cards))

      {:error, player} ->
        conn |> put_flash(:error, "Something's wrong.") |> render("new.html", player: player)
    end
  end
end
