package ex11;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CallInfoCSVWriter {

    private static final String[] headerLines = new String[]{
            "CallerMethodFQIN",
            "CallerBCI",
            "invoketype",
            "CalleeMethodFQIN",
            "CallTargetFQIN",
            "#invokes"
    };

    private final BufferedWriter outFile;

    public CallInfoCSVWriter(final OutputStream outFile) throws IOException {
        this.outFile = new BufferedWriter(new OutputStreamWriter(outFile));
        writeLine(headerLines);
    }

    private static String escapeSpecialCharacters(final String data) {
        final String escapedData = data.replaceAll("\\R", " ");
        if (data.contains(",") || data.contains("\"") || data.contains("'")) {
            return "\"%s\"".formatted(data.replace("\"", "\"\""));
        } else {
            return escapedData;
        }
    }

    private void writeLine(final String... data) throws IOException {
        final String line = Stream.of(data)
                .map(CallInfoCSVWriter::escapeSpecialCharacters)
                .collect(Collectors.joining(","));
        outFile.write(line + "\n");
    }

    public void write(final CallInfo ci, long invokes) throws IOException {
        writeLine(ci.caller(), Long.toString(ci.index()), ci.invokeType(), ci.callee(), ci.callTarget(),
                Long.toString(invokes));
    }
}
