package uebung09.chess;

import java.util.Iterator;

import uebung09.iterator.Array2dIterator;
import uebung09.iterator.SkipNullIterator;


public class Board implements Iterable<Piece>{
    private final Piece[][] field = new Piece[8][8];


    void add(Piece piece) {
        if (piece.getBoard() != this)
            throw new IllegalArgumentException("wrong board");
        final Piece existing = pieceAt(piece.getRow(), piece.getCol());
        if (existing != null)
            throw new IllegalArgumentException("already occupied by " + existing);
        field[piece.getRow() - 1][piece.getCol() - 1] = piece;
    }

    public void printBoard() {
        System.out.println("    1   2   3   4   5   6   7   8");
        System.out.println("  +---+---+---+---+---+---+---+---+");
        for (int row = 1; row <= 8; row++) {
            System.out.print("" + row + " ");
            for (int col = 1; col <= 8; col++) {
                final Piece p = pieceAt(row, col);
                final char c = p == null ? ' ' : p.charRep();
                System.out.print("| " + c + " ");
            }
            System.out.println("|");
            System.out.println("  +---+---+---+---+---+---+---+---+");
        }
    }

    public Piece pieceAt(int row, int col) {
        return field[row - 1][col - 1];
    }

    public void check() {
        for (Piece p1 : this) {
            System.out.println(p1.toString());
            for (Piece p2 : this)
                if (p1 != p2)
                    if (p1.canCapture(p2))
                        System.out.println("   can capture " + p2.toString());
                    else
                        System.out.println("   cannot capture " + p2.toString());
        }
    }

    public String toString() {
        StringBuilder s = new StringBuilder("[");

        for(Piece p : this) {
            s.append(p.toString());
        }

        s.append("]");

        return s.toString();
    }

    @Override
    public Iterator<Piece> iterator() {
        // TODO Auto-generated method stub
        return new SkipNullIterator<>(new Array2dIterator<>(field));
        // throw new UnsupportedOperationException("Unimplemented method 'iterator'");
    }
}
