package org.dicio.sentences_compiler.compiler;

import org.dicio.sentences_compiler.construct.Section;
import org.dicio.sentences_compiler.lexer.Tokenizer;
import org.dicio.sentences_compiler.parser.Parser;
import org.dicio.sentences_compiler.util.CompilerError;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.List;

public abstract class CompilerBase {
    public static String autoGeneratedFileNotice =
            "FILE AUTO-GENERATED BY dicio-sentences-compiler. DO NOT MODIFY.";

    protected final Tokenizer tokenizer;
    protected List<Section> sections = null;

    protected CompilerBase() {
        tokenizer = new Tokenizer();
    }

    public void addInputStream(final InputStreamReader input, final String inputStreamName)
            throws IOException, CompilerError {
        tokenizer.tokenize(input, inputStreamName);
    }

    public List<Section> getSections() throws CompilerError {
        if (sections == null) {
            final Parser parser = new Parser(tokenizer.getTokenStream());
            sections = parser.parse();
        }
        return sections;
    }

    public void compile(final OutputStreamWriter output,
                        final OutputStreamWriter sectionIdsOutput)
            throws IOException, CompilerError {
        if (sectionIdsOutput != null) {
            boolean first = true;
            for (final Section section : getSections()) {
                if (first) {
                    first = false;
                } else {
                    sectionIdsOutput.write(" ");
                }
                sectionIdsOutput.write(section.getSectionId());
            }
            sectionIdsOutput.flush();
        }
    }
}
