package com.banesco.commons.helper;

import io.quarkus.runtime.annotations.RegisterForReflection;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBElement;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Marshaller;
import lombok.extern.slf4j.Slf4j;

import java.io.OutputStream;
import java.util.Objects;


@RegisterForReflection
@Slf4j
public class XMLHelper {

    public static String buildXml(JAXBElement<?> element) {
        try {


            JAXBContext ctx = JAXBContext.newInstance(element.getDeclaredType());
            Marshaller marshaller = ctx.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

            OutputStream output = new OutputStream() {
                private final StringBuilder string = new StringBuilder();

                @Override
                public void write(int b) {
                    this.string.append((char) b);
                }

                public String toString() {
                    return this.string.toString();
                }
            };

            marshaller.marshal(element, output);

            return Objects.requireNonNull(output).toString();
        } catch (JAXBException e) {
            log.warn(e.getMessage());
        }
        return null;
    }
}
