package org.dromara.common.sms.client;

import jakarta.xml.soap.*;

public class SOAPMessageBuilder {

	private SOAPMessage msg;
	private SOAPPart part;
	private SOAPEnvelope envelope;
	private SOAPHeader header;
	private SOAPBody body;

	private SOAPMessageBuilder(String encoding){
		try {
			MessageFactory messageFactory = MessageFactory.newInstance();
			msg = messageFactory.createMessage();
			msg.setProperty("javax.xml.soap.character-set-encoding", encoding);
			part = msg.getSOAPPart();
			envelope = part.getEnvelope();
			header = envelope.getHeader();
			body = envelope.getBody();
		} catch (SOAPException e) {
			e.printStackTrace();
		}
	}

	public static SOAPMessageBuilder newInstance(String encoding){
		return new SOAPMessageBuilder(encoding);
	}

	public SOAPMessageBuilder setNamespace(String name,String uri){
		try {
			envelope.addNamespaceDeclaration(name, uri);
		} catch (SOAPException e) {
			e.printStackTrace();
		}
		return this;
	}

	public SOAPElement addHeaderElements(String localName, String prefix, String uri){
		try {
			Name name = createName(localName, prefix , uri);
			return this.header.addHeaderElement(name);
		} catch (SOAPException e) {
			e.printStackTrace();
		}
		return null;
	}

	public SOAPElement addBodyElements(String localName, String prefix, String uri){
		try {
			Name name = createName(localName, prefix , uri);
			return this.body.addBodyElement(name);
		} catch (SOAPException e) {
			e.printStackTrace();
		}
		return null;
	}

	public SOAPElement addChildElements(SOAPElement soapElement,String localName,String text){
		return addChildElements(soapElement,localName,null,null,text);
	}

	public SOAPElement addChildElements(SOAPElement soapElement,String localName, String prefix, String uri,String text){
		SOAPElement element = null;
		try {
			Name name = createName(localName, prefix , uri);
			element = soapElement.addChildElement(name);
			element.setTextContent(text);
		} catch (SOAPException e) {
			e.printStackTrace();
		}
		return element;
	}

	public Name createName(String localName, String prefix, String uri){
		try {
			return envelope.createName(localName, prefix, uri);
		} catch (SOAPException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Name createName(String localName){
		return createName(localName, null, null);
	}

	public SOAPMessage getSOAPMessage(){
		return this.msg;
	}

	public String toString(){
		return SOAPMessageUtil.getString(this.msg);
	}

}
