package mg.dot.feufaro.musicXML

import java.io.File
import javax.xml.transform.TransformerFactory
import javax.xml.transform.stream.StreamSource
import javax.xml.transform.stream.StreamResult
import java.io.StringReader
import java.io.StringWriter

/**
 * Crée un fichier temporaire avec le nom de fichier suggéré.
 * L'emplacement exact est le répertoire temporaire du système.
 *
 * @param filename Le nom de fichier suggéré (ex: "working.music.xml").
 * @return Le [File] temporaire créé.
 */
fun createTempFileWithFixedName(filename: String): File {
    val tempDir = System.getProperty("java.io.tmpdir") // Répertoire temporaire système
    val tempFile = File(tempDir, filename)

    // S'assurer que le fichier est nouveau ou vide s'il existe déjà
    if (tempFile.exists()) {
        tempFile.delete() // Supprimer l'ancien fichier s'il existe
    }
    tempFile.createNewFile() // Créer le fichier vide

    return tempFile
}

/**
 * Performs an XSLT transformation on XML and XSLT content provided as strings.
 * The transformed XML content is returned as a String.
 *
 * @param xmlInputContent The XML input content as a String.
 * @param xsltContent The XSLT stylesheet content as a String.
 * @param outputFilename The name for the temporary output file. Defaults to "working.music.xml".
 * @return The transformed XML content as a [String].
 * @throws Exception If an error occurs during transformation.
 */
fun performXsltTransformation(
    xmlInputContent: String,
    xsltContent: String,
    outputFilename: String = "working.music.xml" // Default filename for the temp file
): String {
    // Create a temporary file to store the transformed XML.
    // This is useful if the transformer writes to a file, or if you need to debug.
    // However, the primary return will be a String.
    val xmlOutputFile = createTempFileWithFixedName(outputFilename)

    try {
        val factory = TransformerFactory.newInstance()

        // Create StreamSource from StringReaders for in-memory transformation
        val xmlSource = StreamSource(StringReader(xmlInputContent))
        val xsltSource = StreamSource(StringReader(xsltContent))

        // Create a StringWriter to capture the transformed XML output
        val resultWriter = StringWriter()
        val streamResult = StreamResult(resultWriter)

        val transformer = factory.newTransformer(xsltSource)

        // Perform the transformation
        transformer.transform(xmlSource, streamResult)

        // Get the transformed XML content from the StringWriter
        val transformedContent = resultWriter.toString()

        println("Transformation XSLT successful. Transformed content returned as String.")
        // Optionally, write the transformed content to the temporary file for debugging or persistence
        if (outputFilename != "") {
            xmlOutputFile.writeText(transformedContent)
            println("Also saved to temporary file: ${xmlOutputFile.absolutePath}")
        }

        return transformedContent

    } catch (e: Exception) {
        System.err.println("Error during XSLT transformation: ${e.message}")
        e.printStackTrace()
        throw e // Re-throw the exception for calling error handling
    }
}