package de.dhbwstuttgart.sat.asp;


import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Clingo {
    private final List<File> input;
    private static final List<File> programFiles = new ArrayList<>();
    static{
        programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/basis.lp"));
        programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/finiteclosure.lp"));
        programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/subst.lp"));
        programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/reduce.lp"));
        programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/unify.lp"));
        programFiles.add(new File("/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/unifyWithoutWildcards/adapt.lp"));
    }

    public Clingo(List<File> inputFiles){
        this.input = inputFiles;
    }

    /*
    TODO: Clingo per Java Wrapper https://stackoverflow.com/questions/3356200/using-java-to-wrap-over-c
     */
    public String runClingo() throws IOException, InterruptedException {
        String pathToClingo =
                "/home/janulrich/Sync/HiwiJob/ResearchPapers/MasterarbeitStadelmeier/asp/clingo-5.2.1-linux-x86_64/clingo";
        List<String> commands = new ArrayList<>();
        commands.add(pathToClingo);
        //commands.add("--outf=2"); //use JSON-Output
        commands.add("--outf=1"); //use JSON-Output
        for(File file : input){
            commands.add(file.getPath());
        }
        commands.addAll(programFiles.stream().map(f->f.getPath()).collect(Collectors.toList()));

        Process clingo = new ProcessBuilder( commands.toArray(new String[0])).start();
        InputStream output = clingo.getInputStream();
        clingo.waitFor();
        String result = IOUtils.toString(output, StandardCharsets.UTF_8);
        return result;
    }
}
