package cz.muni.reddening;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Class which handles individual reddening calculations by calling Python script
 */
final class CalcHandler {
    private final String map;
    private final String frame;
    private final String x;
    private final String y;
    private final String dist;
    private static final Logger log = LoggerFactory.getLogger(CalcHandler.class);

    /**
     * Constructor for CalcHandler class
     * @param map is the map used for calculations
     * @param frame is the coordinate frame in which coordinates are specified
     * @param x is first coordinate of the frame in degrees
     * @param y is second coordinate of the frame in degrees
     * @param dist is third coordinate of the frame, distance from the Sun, in parsecs
     */
    CalcHandler(String map, String frame, String x, String y,
                String dist) {
        this.map = map;
        this.frame = frame;
        this.x = x;
        this.y = y;
        this.dist = dist;
    }

    /**
     * Runs Python script to calculate Reddening
     * @param configuration is the configuration of the application
     * @return last line of output of python script, meaning the correct calculated reddening or error message
     */
    String runScript(final Configuration configuration) {
        log.info("python script started with " + " " + map +  " " + frame +  " "
                + x  + " " + dist + " " + configuration.getScriptPath());
        ProcessBuilder scriptBuilder = new ProcessBuilder("python",
                configuration.getScriptPath(), map, frame, x, y, dist);
        scriptBuilder.redirectErrorStream(true);
        List<String> results;
        Process script;
        try {
            script = scriptBuilder.start();
            script.waitFor();
            results = new BufferedReader(new InputStreamReader(
                    script.getInputStream()))
                    .lines().collect(Collectors.toList());
        } catch (IOException | InterruptedException e) {
            log.error("exception caught", e);
            return "there has been error calculating data";
        }
        log.info("success " + map + " " + frame + " " + x + " " + y
                + " " + dist + " " + results.get(results.size() - 1));
        return results.get(results.size() - 1);
    }
}
