package de.arxsilex.maptools.converter.desktop

import de.arxsilex.maptools.converter.core.InputFileInfo
import java.io.PrintWriter
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.time.Instant

internal object PreviewProblemLog {
    fun append(source: InputFileInfo?, exception: Throwable): Path? = runCatching {
        val directory = PlatformDirectories.logDirectory()
        Files.createDirectories(directory)
        val destination = directory.resolve("preview.log")
        Files.newBufferedWriter(
            destination,
            StandardCharsets.UTF_8,
            StandardOpenOption.CREATE,
            StandardOpenOption.APPEND,
        ).use { writer ->
            writer.appendLine("${Instant.now()} Vorschaufehler")
            writer.appendLine("Datei: ${source?.path ?: "<kombinierte Vorschau>"}")
            val printer = PrintWriter(writer)
            exception.printStackTrace(printer)
            printer.flush()
            writer.appendLine()
        }
        destination
    }.getOrNull()
}
