package Torello.Java.Build;

import static Torello.Java.C.BRED;
import static Torello.Java.C.RESET;

import Torello.Java.FileNode;
import Torello.Java.RTC;
import Torello.Java.Shell;
import Torello.Java.OSResponse;

import Torello.Java.ReadOnly.ReadOnlyList;

import java.util.stream.Stream;
import java.io.File;
import java.io.IOException;


// All this SINGLE-METHOD-CLASS even does is load the contents of a single
// My/Java/Package/data-files/, and invokes 'javac' on each and every '.java'
// file that is found / identified within that sub-directory-tree.

class CompileDataFilesBuilders
{
    static void compile(
            final BuildPackage          bp,
            final ReadOnlyList<String>  additionalCompilerArgs,
            final String                JAVAC_BIN
        )
        throws IOException
    {
        System.out.println();

        Stream.Builder<String> javacB = Stream.builder();

        if (additionalCompilerArgs != null)
            for (String arg : additionalCompilerArgs) javacB.accept(arg);

        final String dataFilesDirName =
            bp.pkgRootDirectory + "data-files" + File.separator;

        final FileNode fn = FileNode
            .createRoot(dataFilesDirName)
            .loadTree(-1, FileNode.JAVA_FILES, null);

        final int numJavaFiles = fn.countJustFiles();

        if (numJavaFiles == 0)
        {
            System.out.println("No '.java' Files Found");
            return;
        }


        // Places all '.java' Files from the directory tree into the
        // Stream 'javacB'

        fn.flattenJustFiles(RTC.FULLPATH_STREAM_BUILDER(javacB));

        final Shell shell = new Shell(System.out, System.out, null, null);

        final OSResponse r =  (JAVAC_BIN == null)
            ? shell.JAVAC(javacB.build().toArray(String[]::new))
            : null;

        if (r.response != 0)
        {
            System.out.println
                (BRED + "\nERROR CODE: " + r.response + '\n' + RESET);

            System.exit(-1);
        }
    }
}