require_relative "piece"

class Board
  attr_reader :rows

  def initialize
    @null_piece = NullPiece.instance
    @rows = Array.new(8) { Array.new(8, @null_piece) }

    back_row = [Rook, Knight, Bishop, King, Queen, Bishop, Knight, Rook]

    (0..7).each do |col|
      @rows[0][col] = back_row[col].new(:black, self, [0, col])
      @rows[1][col] = Pawn.new(:black, self, [1, col])
      @rows[6][col] = Pawn.new(:white, self, [6, col])
      @rows[7][col] = back_row.reverse[col].new(:white, self, [7, col])
    end
  end

  def [](pos)
    row, col = pos
    @rows[row][col]
  end

  def []=(pos, val)
    row, col = pos
    @rows[row][col] = val
  end

  def move_piece(start_pos, end_pos)
    piece = self[start_pos]
    raise "No piece at that position" if piece.is_a?(NullPiece)
    raise "Invalid move" unless piece.moves.include?(end_pos)
    piece.pos = end_pos
    self[start_pos] = @null_piece
    self[end_pos] = piece
  end
end