defmodule Bwc do
  @moduledoc """
  The core module for the Blank White Cards game.
  """

  alias Bwc.{Repo, Card, Player}

  @repo Repo

  def new_player, do: Player.changeset(%Player{})

  def create_player(attrs), do: Player.changeset(%Player{}, attrs) |> @repo.insert()

  def delete_player(nil), do: {:error, "Player does not exist"}
  def delete_player(%Player{} = player), do: player |> @repo.delete


  def reset, do: Bwc.list_players |> Enum.each(fn(p) -> Bwc.delete_player(p) end)

  def change_name({old_username, new_username}) do
    {:ok, old_player} = old_username |> Bwc.get_or_create_player
    old_player |> Player.changeset(%{username: new_username}) |> @repo.update()
  end

  def list_players, do: @repo.all(Player) |> Enum.filter(fn(p) -> p.username != "Nobody" end)

  def get_player(id), do: @repo.get!(Player, id)

  def get_player_by_username(username), do: get_player_by(%{username: username})

  def get_player_by(params), do: @repo.get_by(Player, params)

  def get_or_create_player(username) do
    case get_player_by(%{username: username}) do
      %Player{} = player ->
        {:ok, player}
      _ ->
        create_player(%{username: username})
    end
  end

  def list_cards, do: @repo.all(Card)

  def get_card(id), do: @repo.get!(Card, id)

  def get_card_by(attrs), do: @repo.get_by(Card, attrs)

  def create_card(attrs), do: Card.changeset(%Card{}, attrs) |> @repo.insert()

  def new_card, do: Card.changeset(%Card{})

  def size, do: Bwc.list_cards() |> length

  def draw_card, do: Bwc.list_cards() |> Enum.random()
  def draw, do: draw_card()

  def delete_card(%Bwc.Card{} = card), do: @repo.delete(card)
  def delete_card!(%Bwc.Card{} = card), do: @repo.delete!(card)

  def update_card(%Bwc.Card{} = card, updates) do
    card
    |> Card.changeset(updates)
    |> @repo.update
  end
end
