"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fillPatternRecursive = exports.fillPattern = void 0;
const constants_1 = require("@scrabble-solver/constants");
const types_1 = require("@scrabble-solver/types");
const fillPattern = (trie, config, pattern, tiles) => {
    if (pattern.getEmptyCellsCount() > tiles.length) {
        return [];
    }
    const results = [];
    (0, exports.fillPatternRecursive)(results, trie, config, pattern, pattern.toString(), tiles);
    return results;
};
exports.fillPattern = fillPattern;
const fillPatternRecursive = (
/** gets mutated when this function is called */
results, trie, config, pattern, word, tiles) => {
    const indexOfFirstCellWithoutTile = pattern.getIndexOfFirstCellWithoutTile();
    if (indexOfFirstCellWithoutTile === -1) {
        if (trie.has(word) && pattern.getCollisions().every((collision) => trie.has(collision.toString()))) {
            results.push(new types_1.FinalPattern(pattern.clone()));
        }
        return;
    }
    for (let index = 0; index < tiles.length; ++index) {
        const tile = tiles[index];
        const previousTile = pattern.cells[indexOfFirstCellWithoutTile].tile;
        pattern.cells[indexOfFirstCellWithoutTile].tile = tile;
        const indexOfNextCellWithoutTile = pattern.getIndexOfFirstCellWithoutTile();
        const indexOfFirstEmptyLetter = word.indexOf(constants_1.EMPTY_CELL);
        const prefix = word.substring(0, indexOfFirstEmptyLetter);
        const suffix = word.substring(indexOfFirstEmptyLetter + 1);
        const characters = tile.isBlank ? config.alphabet : [tile.character];
        for (const character of characters) {
            const newWordPrefix = prefix + character;
            const newWord = newWordPrefix + suffix;
            tile.character = character;
            if (indexOfNextCellWithoutTile === -1) {
                if (trie.has(newWord) && pattern.getCollisions().every((collision) => trie.has(collision.toString()))) {
                    results.push(new types_1.FinalPattern(pattern.clone()));
                }
            }
            else if (trie.hasPrefix(newWordPrefix)) {
                tiles.splice(index, 1);
                (0, exports.fillPatternRecursive)(results, trie, config, pattern, newWord, tiles);
                tiles.splice(index, 0, tile);
            }
        }
        pattern.cells[indexOfFirstCellWithoutTile].tile = previousTile;
    }
};
exports.fillPatternRecursive = fillPatternRecursive;
