package org.soap;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;

import org.biomoby.shared.MobyException;
import org.soap.sax.SOAPFaultParser;

/**
 * A class to represent a SOAP fault
 * 
 * @author Eddie
 * 
 */
public class SOAPFault {

	private String code;

	private String msg;

	private WSRFFault wsrfFault;

	private boolean wsrf = false;

	public SOAPFault() {
		this.code = "";
		this.msg = "";
		this.wsrfFault = new WSRFFault();
	}

	/**
	 * @return the code
	 */
	public String getCode() {
		return code;
	}

	/**
	 * @param code
	 *            the code to set
	 */
	public void setCode(String code) {
		this.code = code;
	}

	/**
	 * @return the msg
	 */
	public String getMsg() {
		return msg;
	}

	/**
	 * @param msg
	 *            the msg to set
	 */
	public void setMsg(String msg) {
		this.msg = msg;
	}

	/**
	 * @return the wsrfFault
	 */
	public WSRFFault getWsrfFault() {
		return wsrfFault;
	}

	/**
	 * @param wsrfFault
	 *            the wsrfFault to set
	 */
	public void setWsrfFault(WSRFFault wsrfFault) {
		this.wsrfFault = wsrfFault;
	}

	public String toString() {
		return "SOAPFault\n\t" + getCode() + ",\n\t" + getMsg() + ",\n\t"
				+ (isWsrf() ? getWsrfFault() : "");
	}

	/**
	 * @return the wsrf
	 */
	public boolean isWsrf() {
		return wsrf;
	}

	/**
	 * @param wsrf
	 *            the wsrf to set
	 */
	public void setWsrf(boolean wsrf) {
		this.wsrf = wsrf;
	}

	/**
	 * 
	 * @param xmlData the xml to parse into a SOAPFault object.  One of byte[], File or String
	 * @return a SOAPFault object obtained by parsing the XML
	 * @throws MobyException
	 *             if there was a problem parsing the xml
	 */
	public static SOAPFault createFromXML(Object xmlData) throws MobyException {

		SOAPFaultParser parser = new SOAPFaultParser();
		if (xmlData instanceof byte[]) {
			return parser.parse(new ByteArrayInputStream((byte[]) xmlData));
		} else if (xmlData instanceof File) {
			try {
				return parser.parse(new FileInputStream((File) xmlData));
			} catch (IOException e) {
				throw new MobyException(e.toString());
			}
		} else if (xmlData instanceof String) {
			return parser.parse(new StringReader((String) xmlData));
		} else
			throw new MobyException(
					"The SOAPFault data should be sent/received either as type String or base64/byte[]. But they are of type '"
							+ xmlData.getClass().getName() + "'.");
	}
}
