package metalexer.metalexer;
import java.io.IOException;
import java.util.SortedSet;
import java.util.TreeSet;

import metalexer.CompilationError;
import metalexer.FileLoader;
import metalexer.ast.Layout;

public class ML2ML {
    public static void main(String[] args) {
        if (args.length != 3) {
            System.err.println("Usage: java ML2ML {layout} {indir} {outdir}");
            System.exit(1);
        }
        String basename = args[0];
        String indir = args[1];
        String outdir = args[2];
        System.out.println("Checking " + basename + " in " + indir);
        SortedSet<CompilationError> errors = new TreeSet<CompilationError>();
        Layout layout = null;
        try {
            FileLoader loader = new FileLoader(indir);
            layout = loader.loadLayout(basename, errors);
            if(layout != null) {
                layout = layout.processInheritance(loader, errors);
                if(layout.getHelper()) {
                    errors.add(layout.makeCompilationError(layout.getName() + " is a helper layout."));
                }
            }
        } catch(IOException e) {
            errors.add(new CompilationError(null, e.getMessage()));
        }
        if(errors.isEmpty()) {
            System.out.println("VALID");
            //TODO-AC: uncomment
            try {
                layout.tidyRuleGroups();
                layout.generateMetaLexer(outdir);
            } catch (IOException e) {
                System.out.println(new CompilationError(null, e.getMessage()));
            }
        } else {
            for(CompilationError error : errors) {
                System.out.println(error);
            }
        }
    }
}
