/*
 * 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.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

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.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import de.uni.rostock.ub.wsrb.edition.webapp.service.SolrService;
import de.uni.rostock.ub.wsrb.edition.webapp.service.XSLTDocumentationService;

@Controller
public class SitemapController {

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

    @Autowired
    XSLTDocumentationService docsService;

    @Autowired
    SolrService solrService;

    @Value("${wsrb.baseurl}")
    private String wsrbBaseurl;

    @Value("#{'${wsrb.transkription.ids}'.split(',')}")
    private List<String> transkriptionIds;

    @GetMapping(path = "/wsrb_sitemap.xml", produces = MediaType.APPLICATION_XML_VALUE)
    public ResponseEntity<StreamingResponseBody> sendSitemapResponse() {
        StreamingResponseBody responseBody = new StreamingResponseBody() {
            @Override
            public void writeTo(OutputStream out) throws IOException {
                try {
                    XMLOutputFactory factory = XMLOutputFactory.newInstance();
                    XMLStreamWriter writer = factory.createXMLStreamWriter(out, "UTF-8");

                    writer.writeStartDocument("UTF-8", "1.0");
                    writer.writeCharacters("\n");
                    writer.writeStartElement("urlset");
                    writer.writeAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");

                    //start page
                    writeURLEntry(writer, wsrbBaseurl);

                    //intro
                    for (String page : docsService.getHtmlBody().keySet()) {
                        if (page.startsWith("intro_")) {
                            writeURLEntry(writer, wsrbBaseurl + "site/" + page);
                        }
                    }

                    writeURLEntry(writer, wsrbBaseurl + "site/" + "daten_tei");
                    writeURLEntry(writer, wsrbBaseurl + "site/" + "buchausgabe");

                    //editions
                    for (String edId : solrService.retrieveAllEditionIDs()) {
                        writeURLEntry(writer, wsrbBaseurl + "edition?id=" + edId);
                    }

                    //transkriptions
                    for (String trId : transkriptionIds) {
                        writeURLEntry(writer, wsrbBaseurl + "transkription?id=" + trId);
                    }
                    writer.writeCharacters("\n");
                    writer.writeEndElement();
                    writer.writeCharacters("\n");
                    writer.writeEndDocument();
                    writer.flush();

                } catch (XMLStreamException ex) {
                    LOGGER.error("SitemapXMLWriter error", ex);
                }
            }
        };
        return ResponseEntity.ok().body(responseBody);

    }

    private void writeURLEntry(XMLStreamWriter writer, String url) throws XMLStreamException {
        writer.writeCharacters("\n  ");
        writer.writeStartElement("url");
        writer.writeStartElement("loc");
        writer.writeCharacters(url);
        writer.writeEndElement();
        writer.writeEndElement();
    }
}
