package pl.polgrabia.demos.crackingcodeinterview.t16x20;

import java.util.function.Consumer;

public class T9Lookup {
    private static final char[][] T9_CODE_MAPPING = new char[][]
            {
                    new char[]{}, // 0
                    new char[]{}, // 1
                    new char[]{'a', 'b', 'c'}, // 2
                    new char[]{'d', 'e', 'f'}, // 3
                    new char[]{'g', 'h', 'i'}, // 4
                    new char[]{'j', 'k', 'l'}, // 5
                    new char[]{'m', 'n', 'o'}, // 6
                    new char[]{'p', 'q', 'r', 's'}, // 7
                    new char[]{'t', 'u', 'v'}, // 8
                    new char[]{'w', 'x', 'y', 'z'}, // 9
            };
    private final RstTree rstTree;

    public T9Lookup(RstTree rstTree) {
        this.rstTree = rstTree;
    }

    public void lookupByCode(int code, Consumer<String> wordConsumer) {
        lookupByCodeInternal(code, "", wordConsumer);
    }

    private void lookupByCodeInternal(int code, String prefix, Consumer<String> wordConsumer) {
        if (code == 0) {
            rstTree.dfsByPrefix(prefix, wordConsumer);
            // logger.info("Got prefix {} to search by", prefix);
        } else {
            int v = code % 10;
            for (int i = 0; i < T9_CODE_MAPPING[v].length; i++) {
                lookupByCodeInternal(code / 10, T9_CODE_MAPPING[v][i] + prefix, wordConsumer);
            }
        }
    }

}
