class GamesController < ApplicationController
  before_action :set_game, only: %i[ show edit update destroy ]

  # GET /games or /games.json
  def index
    @games = Game.all
  end

  # GET /games/1 or /games/1.json
  def show
    @played = GamesPlayer.where(game: @game, played: true)
    @available = GamesPlayer.where(game: @game, played: false)
    @no_available = Array.new

    @game.team.players.each do |p|
      g_p = GamesPlayer.where(game_id: @game.id, player_id: p.id)
      @no_available << p if g_p.empty?
    end

  end

  # GET /games/new
  def new
    @game = Game.new
  end

  # GET /games/1/edit
  def edit
  end

  # GET /games/1/change_status
  def change_status
    game = Game.find(params[:id])

    message = ""
    if params[:act].eql? "availables"
      message = "Disponibilidad para la jornada #{game.matchday}."
      game.state = "availability"
    elsif params[:act].eql? "close"
      message = "Partido de la jornada #{game.matchday} cerrado."
      game.state = "close"
    elsif params[:act].eql? "playing"
      message = "Convocatoria jornada #{game.matchday} abierta."
      game.state = "open"
    end

    if game.save
      respond_to do |format|
        format.html { redirect_to team_url(game.team), notice: message }
      end
    else
      respond_to do |format|
        format.html { redirect_to team_url(game.team), notice: "Jornada no actualizada." }
      end
    end
  end
  # POST /games or /games.json
  def create
    @game = Game.new(game_params)

    respond_to do |format|
      if @game.save
        format.html { redirect_to game_url(@game), notice: "Game was successfully created." }
        format.json { render :show, status: :created, location: @game }
      else
        format.html { render :new, status: :unprocessable_entity }
        format.json { render json: @game.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /games/1 or /games/1.json
  def update
    respond_to do |format|
      if @game.update(game_params)
        format.html { redirect_to game_url(@game), notice: "Game was successfully updated." }
        format.json { render :show, status: :ok, location: @game }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @game.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /games/1 or /games/1.json
  def destroy
    @game.destroy

    respond_to do |format|
      format.html { redirect_to games_url, notice: "Game was successfully destroyed." }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_game
      @game = Game.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def game_params
      params.require(:game).permit(:season_id, :team_id, :matchday, :date, :homesite, :state)
    end
end
