package incheon.res.rdm.com.minwon;

import jakarta.xml.soap.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import java.net.URL;

@Slf4j
@Component("minwonSOAP")
public class MinwonSOAP {

	public SOAPMessage sendSOAP(String msg, String callUrl) throws Exception {

		log.info("::::: sendSOAP in   msg    : "+msg);
		log.info("::::: sendSOAP in   callUrl    : "+callUrl);
		MessageFactory mf = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);

		log.info("::::: MessageFactory.newInstance" );
		SOAPMessage soapMessage = mf.createMessage();
		log.info("::::: createMessage     ::::::" );
		SOAPBody body = soapMessage.getSOAPPart().getEnvelope().getBody();

		log.info("::::: SOAPBody body  11111    ::::::" );

		log.info("[A] before new MinwonUtil");
		MinwonUtil mUtil;
		try {
			mUtil = new MinwonUtil();
			log.info("[B] after new MinwonUtil");
		} catch (Throwable t) {
			log.error("[B-ERR] new MinwonUtil failed", t);
			throw t;
		}

		Document doc;
		try {
			log.info("[C] before getDocument");
			doc = mUtil.getDocument(msg);
			log.info("[D] after getDocument");
		} catch (Throwable t) {
			log.error("[D-ERR] getDocument failed", t);
			throw t;
		}
		try {
			// root localName 확인 (QName 에러면 여기서 단서 바로 나옴)
			Element r = doc.getDocumentElement();
			log.info("[E] root nodeName={}, tagName={}, localName={}, nsURI={}",
					r.getNodeName(), r.getTagName(), r.getLocalName(), r.getNamespaceURI());

			log.info("[F] before body.addDocument");
			body.addDocument(doc);
			log.info("[G] after body.addDocument");
		} catch (Throwable t) {
			log.error("[G-ERR] addDocument failed", t);
			throw t;
		}
		soapMessage.saveChanges();

		log.info("::::: SOAPBody body   222222   ::::::" );

		SOAPConnectionFactory scf = SOAPConnectionFactory.newInstance();
		log.info("::::: SOAPBody body   333333   ::::::" );

		try (SOAPConnection conn = scf.createConnection()) {
			log.info("::::: SOAPConnection conn  ::::::" );

			return conn.call(soapMessage, new URL(callUrl));
		} catch (Exception e) {
			log.error("SOAP call failed. url=" + callUrl, e);
			throw e;
		}
	}
}

