package pl.polgrabia.demos.crackingcodeinterview.t16x20;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.util.Locale;

public class RstTreeLoader {
    private static final Logger logger = LoggerFactory.getLogger(RstTreeLoader.class);
    private final Path path;
    private RstTreeNode rstTree;
    private int counterBad = 0;
    private int counterProcessed = 0;

    public RstTreeLoader(Path path) {
        this.path = path;
    }

    public RstTree load() {
        var rstTree = new RstTree();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(path.toFile())))) {
            String line;
            while ((line = br.readLine()) != null) {
                processLine(rstTree, line);
            }
            logger.info("Processed {} lines, bad ones: {}", counterProcessed, counterBad);
            return rstTree;
        } catch (IOException e) {
            throw new IllegalStateException(
                    "Unable to load word dictionary from path: "
                            + path, e);
        }
    }

    private void processLine(RstTree rstTree, String line) {
        String lowerCasedLine = line.trim()
                .toLowerCase(Locale.ENGLISH);
        if (!lowerCasedLine
                .matches("^[a-z]+$")) {
            counterBad++;
        } else {
            rstTree.add(lowerCasedLine);
        }
        counterProcessed++;
    }
}
