class GamesController < ApplicationController
  before_action :set_game, only: [:show, :edit, :update, :destroy, :play_hand, :join, :start, :my_inventory]

  respond_to :html, :json

  def index
    if params[:table_id]
      @table = Table.find(params[:table_id])
      @games = @table.games
    else
      @games = Game.all.order :id
    end
    respond_with(@games)
  end

  def show
    #TODO: Implement standalone games, without a table?
    #redirect_to @game.table
    respond_with(@game)
  end

  def new
    @game = Game.new
    respond_with(@game)
  end

  def edit
  end

  def play_hand
    # TODO: move this logic out of controller maybe to model(s) ?

    # validate player's turn
    if current_user.soft_token == @game.controlling_player.soft_token

      # Player action: pass
      # TODO: wtf do we need game params for? And why nest hand_type in it?
      # if params[:game]
      if params[:hand_type] == 'Pass'
        @game.set_controlling_player 'next'
        flash[:notice] = 'Successfully passed.'
        @game.save
      # Player action: play_hand
      elsif params[:player_card_ids]
        @cards_to_play = @game.controlling_player.try(:player_cards).order(:value).find(params[:player_card_ids])
        # Instantiate the play
        @play = @game.controlling_player.plays.new
        @play.game_id = @game.id

        # TODO Bug next player fails if inventory is empty
        @next_player_id = @game.next_player_id
        @play.player_cards << @cards_to_play
        if @play.save
          @game.controlling_player_id = @next_player_id
          @game.save
        else
          # TODO: Does anything need to happen here?
          #
          # If play is invalid, remove the cards from the play
          #@play.player_cards.map {|card| card.play_id = nil; card.save}
          # Delete play
          #@play.destroy
        end

        @play.errors.messages.each do |key, msg|
          flash[key] = msg.join
        end
      else 
        # No cards are played
        @cards_to_play = []
      end
    else
      flash[:notice] = 'It is not your turn.'
    end

    respond_to do |format|
      ## TODO: Return status message of attempt to play_hand
      # flash[:notice] = 'I hi'
      format.html { redirect_to(@game.table) }
      format.json { render json: @game }
    end

  end

  def create
    @game = Game.new(title: game_params[:title])
    if game_params[:player_ids]
      game_params[:player_ids].each do |user_id|
        @game.players.new(user_id: user_id)
      end
    end
    @game.save
    respond_with(@game)
  end

  def update
    @game.update(game_params)
    respond_with(@game)
  end

  def destroy
    @game.destroy
    respond_with(@game)
  end

  def play_now
    # First joinable game or create new game
    @game = Game.play_now
    @seats = @game.table.seats.order(:position).map {|s| s.occupied? ? nil : s}
    # @seats = @game.table.seats
    @seat = @seats.compact.last.sit(current_user)
    @seat.save
    redirect_to @game.table
  end

  def join
    @game.add_player_from_user(current_user)
    flash[:notice] = 'Successfully joined game...'
    redirect_to(@game)
  end

  def start
    begin
      @game.start
    rescue StandardError => e
      @game.errors.messages.each do |key, msg|
        flash[key] = msg.join
      end
      redirect_to(@game.table)
      return
    end
    flash[:notice] = 'Game started.'

    redirect_to(@game.table)
  end

  def my_inventory
    @player = @game.players.find_by(user_id: current_user.id)
  end

  private

  def set_game
    @game = Game.find(params[:id])
  end

  def game_params
    params.require(:game).permit(:title, player_ids: [])
  end
end
