defmodule ExMon.Game do
  use Agent

  alias ExMon.Player

  def start(computer, player) do
    initial_value = %{computer: computer, player: player, turn: :player, status: :started}
    Agent.start_link(fn -> initial_value end, name: __MODULE__)
  end

  def update(state) do
    Agent.update(__MODULE__, fn _ -> update_game_status(state) end)
  end

  def info, do: Agent.get(__MODULE__, & &1)

  def player, do: Map.get(info(), :player)

  def turn, do: Map.get(info(), :turn)

  def fetch_player(player), do: Map.get(info(), player)

  defp update_game_status(%{computer: %Player{life: 0}} = state),
    do: Map.put(state, :status, :game_over)

  defp update_game_status(%{player: %Player{life: 0}} = state),
    do: Map.put(state, :status, :game_over)

  defp update_game_status(state) do
    state
    |> Map.put(:status, :continue)
    |> update_turn()
  end

  defp update_turn(%{turn: :computer} = state), do: Map.put(state, :turn, :player)
  defp update_turn(%{turn: :player} = state), do: Map.put(state, :turn, :computer)
end
