class TablesController < ApplicationController
  before_action :set_table, only: [:show, :edit, :update, :destroy, :new_game]

  respond_to :html, :json

  def play_now
    # First empty seat
    @seat = Seat.where(user_soft_token: nil).first
    if @seat
      @seat.sit current_user
    else
      @table = Table.create(title: "Table " + current_user.soft_token[0..4])
      @seat = @table.seats.first
      @seat.sit current_user
    end
    redirect_to @seat.table
    # @game = Game.play_now(current_user)
    # @table = @game.table
    # @seats = @table.seats.order(:position).map {|s| s.occupied? ? nil : s}
    # @seat = @seats.compact.last.sit(current_user)
  end


  # GET /tables
  # GET /tables.json
  def index
    @tables = Table.all
  end

  # GET /tables/1
  # GET /tables/1.json
  def show
    # TODO move this to the game.rb model
    # Clear play to beat if play returns to owner
    # TODO refactor to ensure play for 2nd and 3rd place
    if @game.play_to_beat.try(:player).try(:id) == @game.controlling_player_id
      @game.play_to_beat_id = nil
      @game.save
    end
  end

  def new_game
    @game = @table.add_game
    @game.start
    redirect_to @table
  end

  def tutorial
    flash[:notice] = "Tutorial coming soon!"
    redirect_to root_path
  end

  # GET /tables/new
  def new
    @table = Table.new
  end

  # GET /tables/1/edit
  def edit
  end

  # POST /tables
  # POST /tables.json
  def create
    @table = Table.new(table_params)

    respond_to do |format|
      if @table.save
        format.html { redirect_to @table, notice: 'Table was successfully created.' }
        format.json { render :show, status: :created, location: @table }
      else
        format.html { render :new }
        format.json { render json: @table.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /tables/1
  # PATCH/PUT /tables/1.json
  def update
    respond_to do |format|
      if @table.update(table_params)
        format.html { redirect_to @table, notice: 'Table was successfully updated.' }
        format.json { render :show, status: :ok, location: @table }
      else
        format.html { render :edit }
        format.json { render json: @table.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /tables/1
  # DELETE /tables/1.json
  def destroy
    @table.destroy
    respond_to do |format|
      format.html { redirect_to tables_url, notice: 'Table was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_table
      @table = Table.find(params[:id])
      @game = @table.current_game
      @seats = @table.seats.order(:id)
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def table_params
      params.require(:table).permit(:title)
    end
end
