/*
 * Copyright (c) 2025 Rostock University Library
 * Licensed under the MIT License. See LICENSE file in the project root.
 */
package de.uni.rostock.ub.wsrb.edition.webapp.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Map;

import javax.xml.transform.stream.StreamSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import de.uni.rostock.ub.wsrb.edition.webapp.util.WSRBUtil;
import jakarta.annotation.PostConstruct;
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XdmAtomicValue;
import net.sf.saxon.s9api.XdmMap;
import net.sf.saxon.s9api.XdmValue;
import net.sf.saxon.s9api.Xslt30Transformer;
import net.sf.saxon.s9api.XsltCompiler;
import net.sf.saxon.s9api.XsltExecutable;

@Service
public class XSLTTexteinheitService {

    private static final Logger LOGGER = LoggerFactory.getLogger(XSLTTexteinheitService.class);

    @Autowired
    DataService dataService;

    @Value("${wsrb.folder.teixml}")
    private String teixmlFolder;

    @Value("${wsrb.folder.xslt}")
    private String xsltFolder;

    XsltExecutable xslTranscriptionFragements;

    Processor processor = new Processor(false);

    @PostConstruct
    private void init() {
        try (InputStream instrXsltTE = getClass().getResourceAsStream(xsltFolder + "edition/html4texteinheit.xsl")) {
            XsltCompiler compiler = processor.newXsltCompiler();
            xslTranscriptionFragements = compiler.compile(new StreamSource(instrXsltTE));
        } catch (SaxonApiException | IOException e) {
            LOGGER.error("Initialisation error:", e);
        }
    }

    public String createTranscriptionFragments(@NonNull String tes, @NonNull String labels) {
        StringWriter sw = new StringWriter();
        String[] arrTes = tes.split("\\|");
        String[] arrLabels = labels.split("\\|");

        sw.append("<div class=\"row row-cols-2 g-2\">\n");
        try {
            if (arrTes.length == arrLabels.length) {
                for (int i = 0; i < arrTes.length; i++) {
                    String teId = arrTes[i];
                    String docId = teId.substring(0, 12);
                    String label = arrLabels[i];
                    Xslt30Transformer transformer = xslTranscriptionFragements.load30();

                    Map<QName, XdmValue> params = Map.ofEntries(
                        Map.entry(new QName("te_id"), new XdmAtomicValue(teId.replace(",", " "))),
                        Map.entry(new QName("label"), new XdmAtomicValue(label)),
                        Map.entry(new QName("map_id2line"), XdmMap.makeMap(dataService.retrieveIdToLineMap())));
                    //check if the serializer used append if called multiple times;

                    StringWriter sw1 = new StringWriter();
                    transformer.setStylesheetParameters(params);
                    String path = teixmlFolder + "transkriptionen/" + docId + WSRBUtil.TEI_FILE_EXTENSION;
                    try (InputStream instrTranskriptionXml = getClass().getResourceAsStream(path)) {
                        transformer.transform(new StreamSource(instrTranskriptionXml),
                            WSRBUtil.createSerializer(processor, sw1));
                        sw.append(sw1.toString());
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("Could not create transcription fragment", e);
        }
        sw.append("\n</div>");
        return sw.toString();
    }

}
