import { GameTurn } from '../../models/game.models';

export function getPieceAtSquare(fen: string, targetSquare: string): string | null {
  const placement = fen.split(' ')[0] ?? '';
  const rows = placement.split('/');
  if (rows.length !== 8 || targetSquare.length !== 2) {
    return null;
  }

  const file = targetSquare.charCodeAt(0) - 97;
  const rank = Number(targetSquare[1]);
  const rowIndex = 8 - rank;

  if (Number.isNaN(rank) || file < 0 || file > 7 || rowIndex < 0 || rowIndex > 7) {
    return null;
  }

  let column = 0;
  for (const symbol of rows[rowIndex]) {
    if (symbol >= '1' && symbol <= '8') {
      column += Number(symbol);
      continue;
    }

    if (column === file) {
      return symbol;
    }

    column += 1;
  }

  return null;
}

export function isPieceColor(pieceCode: string, turn: GameTurn): boolean {
  const isWhitePiece = pieceCode === pieceCode.toUpperCase();
  return (turn === 'white' && isWhitePiece) || (turn === 'black' && !isWhitePiece);
}
