package leigh.tesseract;

import leigh.mecha.log.MechaLogger;
import leigh.mecha.log.MechaLoggerFactory;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * This class implements a basic file-based result writer for {@link Tesseract}.
 *
 * @author Alex Leigh
 */
public class FileResultWriter implements ResultWriter {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(FileResultWriter.class);
    private final Path outputDir;

    public FileResultWriter(Path outputDir) throws IOException {
        this.outputDir = outputDir;
        File outputFile = outputDir.toFile();
        if (!outputFile.exists()) {
            if (!outputFile.mkdirs()) {
                throw new IOException("Unable to create output directory: " + outputDir);
            }
        }
    }

    @Override
    public void output(String hostname, String result, int returnCode) throws IOException {
        Path out = Paths.get(outputDir.toString(), hostname + ".txt");
        logger.debug("Writing output. [hostname: {}] [path: {}] [len: {}]", hostname, out, result.length());
        BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(out.toFile()));
        os.write(result.getBytes(StandardCharsets.UTF_8));
        os.close();
    }

    @Override
    public void finish() {
        // Intentionally Blank
    }
}
