import 'dart:math';

import 'package:solitaire_game/entities/tile.dart';
import 'package:solitaire_game/provider/data.dart';

class BoardUtils {
  static printGrid(List cells) {
    String textBoard = ' ';
    String textHole = '·';
    String textPeg = 'o';

    print('');
    print('-------');
    for (var rowIndex = 0; rowIndex < cells.length; rowIndex++) {
      String row = '';
      for (var colIndex = 0; colIndex < cells[rowIndex].length; colIndex++) {
        String textCell = textBoard;
        Tile? tile = cells[rowIndex][colIndex];
        if (tile != null) {
          textCell = tile.hasPeg ? textPeg : textHole;
        }
        row += textCell;
      }
      print(row);
    }
    print('-------');
    print('');
  }

  static List<List<Tile?>> createBoardFromSavedState(Data myProvider, String savedBoard) {
    List<List<Tile?>> board = [];
    int boardSize = pow((savedBoard.length), 1 / 2).round();
    myProvider.updateBoardSize(boardSize);

    String textBoard = ' ';
    String textPeg = 'o';

    int index = 0;
    for (var rowIndex = 0; rowIndex < boardSize; rowIndex++) {
      List<Tile?> row = [];
      for (var colIndex = 0; colIndex < boardSize; colIndex++) {
        String stringValue = savedBoard[index++];
        if (stringValue == textBoard) {
          row.add(null);
        } else {
          row.add(Tile(rowIndex, colIndex, (stringValue == textPeg)));
        }
      }
      board.add(row);
    }

    return board;
  }

  static createNewBoard(Data myProvider) {
    List<String> templateEnglish = [
      '  ooo  ',
      '  ooo  ',
      'ooooooo',
      'ooo·ooo',
      'ooooooo',
      '  ooo  ',
      '  ooo  ',
    ];

    List<List<Tile?>> grid = [];
    int row = 0;
    templateEnglish.forEach((String line) {
      List<Tile?> gridLine = [];
      int col = 0;
      line.split("").forEach((String tileCode) {
        gridLine.add(tileCode == ' ' ? null : new Tile(row, col, (tileCode == 'o')));
        col++;
      });
      row++;
      grid.add(gridLine);
    });

    printGrid(grid);

    myProvider.resetGame();
    myProvider.updateBoard(grid);
  }
}