package org.biomoby.w3c.addressing;

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.w3c.addressing.sax.EndpointReferenceParser;

/**
 * This class models the EndpointReference object described in the WSRF
 * addressing protocol. Only things relevant to BioMOBY async services has been
 * included.
 * 
 * @author Eddie
 * 
 */
public class EndpointReference {

	// the address to be used in the To field of a SOAP header element
	private String address = "";

	// The service invocation id as per the BioMOBY async proposal
	private String serviceInvocationId = "";

	/**
	 * Default Constructor
	 * 
	 */
	public EndpointReference() {
	}

	/**
	 * @return the address - this is meant to be used as the 'To' address when
	 *         interacting with WSRF
	 */
	public String getAddress() {
		return address;
	}

	/**
	 * @param address
	 *            the address to set
	 */
	public void setAddress(String address) {
		this.address = address.trim();
	}

	/**
	 * @return the serviceInvocationId
	 */
	public String getServiceInvocationId() {
		return serviceInvocationId;
	}

	/**
	 * @param serviceInvocationId
	 *            the serviceInvocationId to set
	 */
	public void setServiceInvocationId(String serviceInvocationId) {
		this.serviceInvocationId = serviceInvocationId.trim();
	}

	/**
	 * 
	 * @param xmlData
	 *            the xml to be used in creating the EndpointReference object
	 * @return an EndpointReference object
	 * @throws MobyException
	 *             if there is a problem parsing the XML
	 */
	public static EndpointReference createFromXML(Object xmlData)
			throws MobyException {

		EndpointReferenceParser parser = new EndpointReferenceParser();
		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 EPR data should be sent/received either as type String or base64/byte[]. But they are of type '"
							+ xmlData.getClass().getName() + "'.");
	}

	/*
	 * (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		return "EPR {To: " + getAddress() + ", id: " + getServiceInvocationId()
				+ "}";
	}
}
