/***********************************************************
Copyright (C) 2018 VeriSign, Inc.

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

http://www.verisign.com/nds/naming/namestore/techdocs.html
 ***********************************************************/
package com.verisign.epp.codec.registry.v01;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import com.verisign.epp.codec.gen.EPPCodecComponent;
import com.verisign.epp.codec.gen.EPPCodecException;
import com.verisign.epp.codec.gen.EPPDecodeException;
import com.verisign.epp.codec.gen.EPPEncodeException;
import com.verisign.epp.codec.gen.EPPUtil;
import com.verisign.epp.util.EPPCatFactory;
import com.verisign.epp.util.EqualityUtil;

/**
 * EPP namespace URIs of the objects and object extensions supported by the
 * server based on RFC 5730. The {@code EPPRegistryServices} contains the
 * following lists:<br>
 * <ul>
 * <li>One or more object {@code String}s that contain namespace URIs
 * representing the objects that the server is capable of managing for the zone
 * with the required "required" attribute that defines whether the server
 * requires the use of object represented by the URI.
 * <li>An optional {@code EPPRegistryServicesExt} object that contains one or
 * more {@code String}s that contain namespace URIs representing object
 * extensions support by the server for the zone with the required "required"
 * attribute that defines whether the server requires the use of the object
 * extension represented by the URI.
 * </ul>
 */
public class EPPRegistryServices implements EPPCodecComponent {

	/**
	 * Logger
	 */
	private static Logger cat = Logger.getLogger(EPPRegistryServices.class.getName(),
	      EPPCatFactory.getInstance().getFactory());

	/**
	 * XML local name for {@code EPPRegistryServices}.
	 */
	public static final String ELM_LOCALNAME = "services";

	/**
	 * XML root tag for {@code EPPRegistryServices}.
	 */
	public static final String ELM_NAME = EPPRegistryMapFactory.NS_PREFIX + ":" + ELM_LOCALNAME;

	/**
	 * List of {@link EPPRegistryObjURI} instances that contain the object
	 * namespace URIs
	 */
	private List<EPPRegistryObjURI> objURIs = new ArrayList<EPPRegistryObjURI>();

	/**
	 * Optional extension services attribute
	 */
	private EPPRegistryServicesExt extension;

	/**
	 * Default constructor. At least one object URI must be set prior to calling
	 * {@link #encode(Document)}.
	 */
	public EPPRegistryServices() {
	}

	/**
	 * Constructor that takes the list of object URIs for the zone.
	 *
	 * @param aObjURIs
	 *           {@link List} of {@link EPPRegistryObjURI} instances
	 */
	public EPPRegistryServices(List<EPPRegistryObjURI> aObjURIs) {
		this.setObjURIs(aObjURIs);
	}

	/**
	 * Encode a DOM Element tree from the attributes of the
	 * {@code EPPRegistryServices} instance.
	 *
	 * @param aDocument
	 *           DOM Document that is being built. Used as an Element factory.
	 *
	 * @return Element Root DOM Element representing the
	 *         {@code EPPRegistryServices} instance.
	 *
	 * @exception EPPEncodeException
	 *               - Unable to encode {@code EPPRegistryServices} instance.
	 */
	@Override
	public Element encode(Document aDocument) throws EPPEncodeException {
		if (this.objURIs == null || this.objURIs.size() == 0) {
			throw new EPPEncodeException("Invalid state on EPPRegistryServices.encode: objURIs is required.");
		}
		Element root = aDocument.createElementNS(EPPRegistryMapFactory.NS, ELM_NAME);

		// Object URIs
		EPPUtil.encodeCompList(aDocument, root, this.objURIs);

		// Extension Services
		EPPUtil.encodeComp(aDocument, root, this.extension);

		return root;
	}

	/**
	 * Decode the {@code EPPRegistryServices} attributes from the aElement DOM
	 * Element tree.
	 *
	 * @param aElement
	 *           Root DOM Element to decode {@code EPPRegistryServices} from.
	 *
	 * @exception EPPDecodeException
	 *               Unable to decode aElement
	 */
	@Override
	public void decode(Element aElement) throws EPPDecodeException {
		// Object URIs
		this.objURIs = EPPUtil.decodeCompList(aElement, EPPRegistryMapFactory.NS, EPPRegistryURI.ELM_OBJ_URI,
		      EPPRegistryObjURI.class);

		// Extension Services
		this.extension = (EPPRegistryServicesExt) EPPUtil.decodeComp(aElement, EPPRegistryMapFactory.NS,
		      EPPRegistryServicesExt.ELM_NAME, EPPRegistryServicesExt.class);
	}

	/**
	 * implements a deep {@code EPPRegistryServices} compare.
	 *
	 * @param aObject
	 *           {@code EPPRegistryServices} instance to compare with
	 *
	 * @return {@code true} if this object is the same as the aObject argument;
	 *         {@code false} otherwise
	 */
	@Override
	public boolean equals(Object aObject) {
		if (!(aObject instanceof EPPRegistryServices)) {
			return false;
		}

		EPPRegistryServices theComp = (EPPRegistryServices) aObject;

		// Object URIs
		if (!EPPUtil.equalLists(this.objURIs, theComp.objURIs)) {
			cat.error("EPPRegistryServices.equals(): objURIs not equal");
			return false;
		}

		// Extension Services
		if (!EqualityUtil.equals(this.extension, theComp.extension)) {
			cat.error("EPPRegistryServices.equals(): extension not equal");
			return false;
		}

		return true;
	}

	/**
	 * Clone {@code EPPRegistryServices}.
	 *
	 * @return clone of {@code EPPRegistryServices}
	 *
	 * @exception CloneNotSupportedException
	 *               standard Object.clone exception
	 */
	@Override
	public Object clone() throws CloneNotSupportedException {
		EPPRegistryServices clone = (EPPRegistryServices) super.clone();

		// Object URIs
		if (this.objURIs != null) {
			clone.objURIs = (List<EPPRegistryObjURI>) ((ArrayList) this.objURIs).clone();
		}

		// Extension Services
		if (this.extension != null) {
			clone.extension = (EPPRegistryServicesExt) this.extension.clone();
		}

		return clone;
	}

	/**
	 * Implementation of {@code Object.toString}, which will result in an
	 * indented XML {@code String} representation of the concrete
	 * {@code EPPCodecComponent}.
	 *
	 * @return Indented XML {@code String} if successful; {@code ERROR}
	 *         otherwise.
	 */
	@Override
	public String toString() {
		return EPPUtil.toString(this);
	}

	/**
	 * Gets the namespace URIs representing the objects that the server is
	 * capable of managing for the zone.
	 *
	 * @return {@link List} of {@link EPPRegistryURI} instances.
	 */
	public List<EPPRegistryObjURI> getObjURIs() {
		return this.objURIs;
	}

	/**
	 * Sets the namespace URIs representing the objects that the server is
	 * capable of managing for the zone.
	 *
	 * @param aObjURIs
	 *           {@link List} of {@link EPPRegistryURI} instances.
	 */
	public void setObjURIs(List<EPPRegistryObjURI> aObjURIs) {
		if (aObjURIs == null) {
			this.objURIs = new ArrayList<EPPRegistryObjURI>();
		}
		else {
			this.objURIs = aObjURIs;
		}
	}

	/**
	 * Adds an object namespace URI to the list of object namespace URIs.
	 *
	 * @param aURI
	 *           URI to add to list
	 */
	public void addObjURI(EPPRegistryObjURI aURI) {
		this.objURIs.add(aURI);
	}

	/**
	 * Gets the extension services.
	 *
	 * @return Extension services if defined; {@code null} otherwise.
	 */
	public EPPRegistryServicesExt getExtension() {
		return this.extension;
	}

	/**
	 * Sets the extension services.
	 *
	 * @param aExtension
	 *           Extension services to set.
	 */
	public void setExtension(EPPRegistryServicesExt aExtension) {
		this.extension = aExtension;
	}

	/**
	 * Abstract class that represents an object or extension URI.
	 */
	public static abstract class EPPRegistryURI implements EPPCodecComponent {

		/**
		 * XML local name for object URI.
		 */
		public static final String ELM_OBJ_URI_LOCALNAME = "objURI";

		/**
		 * XML element used for an object URI.
		 */
		public final static String ELM_OBJ_URI = EPPRegistryMapFactory.NS_PREFIX + ":" + ELM_OBJ_URI_LOCALNAME;

		/**
		 * XML local name for extension URI.
		 */
		public static final String ELM_EXT_URI_LOCALNAME = "extURI";

		/**
		 * XML element used for an extension URI.
		 */
		public final static String ELM_EXT_URI = EPPRegistryMapFactory.NS_PREFIX + ":" + ELM_EXT_URI_LOCALNAME;

		/**
		 * XML "required" attribute
		 */
		public final static String ATTR_REQUIRED = "required";

		/**
		 * Required attribute value
		 */
		private Boolean required = null;

		/**
		 * Object or extension URI
		 */
		private String uri = null;

		/**
		 * Default constructor. The "required" attribute must be set and the URI
		 * must be set prior to calling {@link #encode(Document)}.
		 */
		public EPPRegistryURI() {
		}

		/**
		 * Constructor that takes the two required attributes for the URI and the
		 * required attribute.
		 *
		 * @param aUri
		 *           The object or extension URI
		 * @param aRequired
		 *           {@code true} if the use of the object or extension URI is
		 *           required; {@code false} otherwise.
		 */
		public EPPRegistryURI(String aUri, Boolean aRequired) {
			this.uri = aUri;
			this.required = aRequired;
		}

		/**
		 * Gets the name of the root XML element.
		 *
		 * @return {@link #ELM_OBJ_URI} for an object URI and {@link #ELM_EXT_URI}
		 *         for an extension URI.
		 */
		abstract public String getRootName();

		/**
		 * Encode a DOM Element tree from the attributes of the
		 * {@code EPPRegistryURI} instance.
		 *
		 * @param aDocument
		 *           DOM Document that is being built. Used as an Element factory.
		 *
		 * @return Element Root DOM Element representing the
		 *         {@code EPPRegistryURI} instance.
		 *
		 * @exception EPPEncodeException
		 *               - Unable to encode {@code EPPRegistryURI} instance.
		 */
		@Override
		public Element encode(Document aDocument) throws EPPEncodeException {
			try {
				validateState();
			}
			catch (EPPCodecException e) {
				throw new EPPEncodeException("Invalid state on " + this.getClass().getName() + ".encode: " + e);
			}
			Element root = aDocument.createElementNS(EPPRegistryMapFactory.NS, getRootName());

			// URI
			Text currVal = aDocument.createTextNode(this.uri);
			root.appendChild(currVal);

			// Required
			root.setAttribute(ATTR_REQUIRED, this.required.toString());

			return root;
		}

		/**
		 * Decode the {@code EPPRegistryURI} attributes from the aElement DOM
		 * Element tree.
		 *
		 * @param aElement
		 *           Root DOM Element to decode {@code EPPRegistryURI} from.
		 *
		 * @exception EPPDecodeException
		 *               Unable to decode aElement
		 */
		@Override
		public void decode(Element aElement) throws EPPDecodeException {
			// URI
			this.uri = aElement.getFirstChild().getNodeValue();

			// Required
			this.required = Boolean.valueOf(EPPUtil.decodeBooleanAttr(aElement, ATTR_REQUIRED));
		}

		/**
		 * Validates the state prior to encoding the object in
		 * {@link #encode(Document)} by validating that the required attributes
		 * have been set. The {@link EPPCodecException} is thrown if a required
		 * attribute is not set.
		 *
		 * @throws EPPCodecException
		 *            One of the required attributes has not been set.
		 */
		private void validateState() throws EPPCodecException {
			// URI
			if (this.uri == null || this.uri.trim().length() == 0) {
				throw new EPPCodecException("uri attribute is not set");
			}

			// Required
			if (this.required == null) {
				throw new EPPCodecException("required attribute is not set");
			}
		}

		/**
		 * Clone {@code EPPRegistryURI}.
		 *
		 * @return clone of {@code EPPRegistryURI}
		 *
		 * @exception CloneNotSupportedException
		 *               standard Object.clone exception
		 */
		@Override
		public Object clone() throws CloneNotSupportedException {
			return super.clone();
		}

		/**
		 * implements a deep {@code EPPRegistryURI} compare.
		 *
		 * @param aObject
		 *           {@code EPPRegistryURI} instance to compare with
		 *
		 * @return {@code true} if this object is the same as the aObject
		 *         argument; {@code false} otherwise
		 */
		@Override
		public boolean equals(Object aObject) {
			if (!(aObject instanceof EPPRegistryURI)) {
				return false;
			}

			EPPRegistryURI theComp = (EPPRegistryURI) aObject;

			// URI
			if (!EqualityUtil.equals(this.uri, theComp.uri)) {
				cat.error(this.getClass().getName() + ".equals(): uri not equal");
				return false;
			}

			// Required
			if (!EqualityUtil.equals(this.required, theComp.required)) {
				cat.error(this.getClass().getName() + ".equals(): required not equal");
				return false;
			}

			return true;
		}

		/**
		 * Implementation of {@code Object.toString}, which will result in an
		 * indented XML {@code String} representation of the concrete
		 * {@code EPPCodecComponent}.
		 *
		 * @return Indented XML {@code String} if successful; {@code ERROR}
		 *         otherwise.
		 */
		@Override
		public String toString() {
			return EPPUtil.toString(this);
		}

		/**
		 * Gets the "required" attribute value.
		 *
		 * @return {@code true} if use of the URI is required; {@code false}
		 *         otherwise. {@code null} if the attribute has not been set.
		 */
		public Boolean getRequired() {
			return this.required;
		}

		/**
		 * Sets the "required" attribute value.
		 *
		 * @param aRequired
		 *           {@code true} if use of the URI is required; {@code false}
		 *           otherwise.
		 */
		public void setRequired(Boolean aRequired) {
			this.required = aRequired;
		}

		/**
		 * Gets the object or extension URI.
		 *
		 * @return Object or extension URI if defined; {@code null} otherwise.
		 */
		public String getUri() {
			return this.uri;
		}

		/**
		 * Sets the object or extension URI.
		 *
		 * @param aUri
		 *           Object or extension URI value.
		 */
		public void setUri(String aUri) {
			this.uri = aUri;
		}
	}

	/**
	 * Object service URI that includes the URI value and a "required" attribute
	 * that indicates whether use of the object service is required.
	 */
	public static class EPPRegistryObjURI extends EPPRegistryURI {

		/**
		 * Default constructor. The "required" attribute must be set and the URI
		 * must be set prior to calling {@link #encode(Document)}.
		 */
		public EPPRegistryObjURI() {
		}

		/**
		 * Constructor that takes the two required attributes for the URI and the
		 * required attribute.
		 *
		 * @param aUri
		 *           The object URI
		 * @param aRequired
		 *           {@code true} if the use of the object URI is required;
		 *           {@code false} otherwise.
		 */
		public EPPRegistryObjURI(String aUri, Boolean aRequired) {
			super(aUri, aRequired);
		}

		/**
		 * Gets the name of the root XML element.
		 *
		 * @return {@link #ELM_OBJ_URI} for the object URI.
		 */
		@Override
		public String getRootName() {
			return EPPRegistryURI.ELM_OBJ_URI;
		}

		/**
		 * implements a deep {@code EPPRegistryObjURI} compare.
		 *
		 * @param aObject
		 *           {@code EPPRegistryObjURI} instance to compare with
		 *
		 * @return {@code true} if this object is the same as the aObject
		 *         argument; {@code false} otherwise
		 */
		@Override
		public boolean equals(Object aObject) {
			return super.equals(aObject);
		}

		/**
		 * Returns the XML namespace associated with the {@code EPPCodecComponent}
		 * .
		 *
		 * @return XML namespace for the {@code EPPCodecComponent}.
		 */
		@Override
		public String getNamespace() {
			return EPPRegistryMapFactory.NS;
		}

	}

	/**
	 * Returns the XML namespace associated with the {@code EPPCodecComponent}.
	 *
	 * @return XML namespace for the {@code EPPCodecComponent}.
	 */
	@Override
	public String getNamespace() {
		return EPPRegistryMapFactory.NS;
	}

}
