import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.regex.Pattern;


public class MatchingFileWriter {

    private String filename;
    private String sourceFileName;
    private List<String> comments;
    private List<String> headers;
    private List<List<String>> allResults;

    public MatchingFileWriter(String filename, MatchingResult result){
        if(!filename.matches(".*\\.csv")){
            filename = filename + ".csv";
        }
        this.filename = filename;
        this.sourceFileName = result.getSourceFileName();
        this.comments = result.getComments();
        this.headers = result.getHeaders();
        this.allResults = result.getAllResults();
    }

    public void writeErrorRateToTerminal(){
        for(String s: comments){
            if(s.matches("(Pairing error rate: )(\\d*.\\d+)")){
                System.out.println(s);
            }
        }
    }
    public void writeResultsToFile(){
        String[] headerStrings = new String[headers.size()];
        for(int i = 0; i < headers.size(); i++){
            headerStrings[i] = headers.get(i);
        }
        CSVFormat resultsFileFormat = CSVFormat.Builder.create()
                .setCommentMarker('#')
                //.setHeader(headerStrings)
                .build();
        try(BufferedWriter writer = Files.newBufferedWriter(Path.of(filename), StandardOpenOption.CREATE_NEW);
            CSVPrinter printer = new CSVPrinter(writer, resultsFileFormat);
        ){
            for(String comment: comments){
                printer.printComment(comment);
            }
            allResults.add(0, headers);
            printer.printRecords(allResults);

        } catch(IOException ex){
            System.out.println("Could not make new file named "+filename);
            System.err.println(ex);
        }
    }
}
