package cz.muni.reddening;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

/**
 *  Class that handles and processes file input and file output
 */
public final class FileHandler {
    private static final Logger log = LoggerFactory.getLogger(FileHandler.class);
    private final MultipartFile file;
    private final String law;
    private final String frame;

    /**
     *  Constructor for class FileHandler
     * @param file is the input file we need to make calculations
     * @param law is the reddening law used for our calculations
     * @param frame is the coordinate frame used by file
     */
    FileHandler(MultipartFile file, String law, String frame) {
        this.file = file;
        this.law = law;
        this.frame = frame;
    }

    /**
     * Creates output file based on input file
     * @param configuration is the configuration of the application
     * @return String value from which output file gets formed
     * @throws IOException if we are unable to read the input file
     */
    public String output(final Configuration configuration) throws IOException {
        log.info("fileHandler began working");
        StringBuilder writer = new StringBuilder();
        BufferedReader br = (new BufferedReader(new InputStreamReader(
                file.getInputStream(), StandardCharsets.UTF_8)));
        for (String line : br.lines().collect(Collectors.toList())) {
            String[] parameters = line.split(" ");
            writer.append(line).append(" ");
            if (parameters.length == 3) {
                writer.append(new CalcHandler(law, frame, parameters[0],
                        parameters[1], parameters[2]).runScript(configuration));
            } else if (!line.isEmpty()) {
                writer.append("error");
            }
            writer.append("\n");
        }
        log.info("success");
        return writer.toString();
    }
}
