/***********************************************************
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-0107  USA

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

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

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

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;

/**
 * Represents the Internationalized Domain Name (IDN) policy information. The
 * &lt;registry:idn&gt; must contain the following child elements:<br>
 * <br>
 *
 * <ul>
 * <li>&lt;registry:idnVersion&gt; - The OPTIONAL server unique version of the
 * IDN language rules. Use {@link #getIdnVersion()} and
 * {@link #setIdnVersion(String)} to get and set the element.</li>
 * <li>&lt;registry:idnaVersion&gt; - An Internationalizing Domain Names in
 * Applications (IDNA) version supported by the server. IDNA represents a
 * collection of documents that describe the protocol and usage for
 * Internationalized Domain for Applications like IDNA 2003, with value of 2003,
 * or IDNA 2008, with value of 2008. Use {@link #getIdnaVersion()} and
 * {@link #setIdnaVersion(String)} to get and set the element.</li>
 * <li>&lt;registry:unicodeVersion&gt; - The Unicode version supported by the
 * server like the value of "6.0" for Unicode 6.0. Use
 * {@link #getUnicodeVersion()} and {@link #setUnicodeVersion(String)} to get
 * and set the element.</li>
 * <li>&lt;registry:encoding&gt; - The OPTIONAL encoding for transforming
 * Unicode characters uniquely and reversibly into DNS compatible characters
 * with a default value of "Punycode". Use {@link #getEncoding()} and
 * {@link #setEncoding(String)} to get and set the element.</li>
 * <li>&lt;registry:commingleAllowed&gt; - An OPTIONAL boolean value that
 * indicates whether commingling of scripts is allowed with a default value of
 * "false". Use {@link #getCommingleAllowed()} and
 * {@link #setCommingleAllowed(Boolean)} to get and set the element.</li>
 * <li>&lt;registry:language&gt; - Zero or more &lt;registry:language&gt;
 * elements that defines the supported language codes and character code point
 * policy. Use {@link #getLanguages()} and {@link #setLanguages(List)} to get
 * and set the element. Use {@link #addLanguage(EPPRegistryLanguage)} to add
 * one language policy to the existing list.</li>
 * </ul>
 *
 * @see com.verisign.epp.codec.registry.v02.EPPRegistryDomain
 * @see com.verisign.epp.codec.registry.v02.EPPRegistryLanguage
 */
public class EPPRegistryIDN implements EPPCodecComponent {

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

	/**
	 * Constant for the {@code EPPRegistryIDN} local name
	 */
	public static final String ELM_LOCALNAME = "idn";

	/**
	 * Constant for the {@code EPPRegistryIDN} (prefix and local name)
	 */
	public static final String ELM_NAME = EPPRegistryMapFactory.NS_PREFIX + ":" + ELM_LOCALNAME;

	/**
	 * XML Element Name of {@code idnVersion} attribute.
	 */
	public static final String ELM_IDN_VERSION = "idnVersion";

	/**
	 * XML Element Name of {@code idnaVersion} attribute.
	 */
	public static final String ELM_IDNA_VERSION = "idnaVersion";

	/**
	 * XML Element Name of {@code unicodeVersion} attribute.
	 */
	public static final String ELM_UNICODE_VERSION = "unicodeVersion";

	/**
	 * XML Element Name of {@code encoding} attribute.
	 */
	public static final String ELM_ENCODING = "encoding";

	/**
	 * XML Element Name of {@code commingleAllowed} attribute.
	 */
	public static final String ELM_COMMINGLE_ALLOWED = "commingleAllowed";

	/**
	 * String representation of idnVersion
	 */
	private String idnVersion = null;

	/**
	 * String representation of idnaVersion
	 */
	private String idnaVersion = null;

	/** String representation of unicodeVersion */
	private String unicodeVersion = null;

	/**
	 * Whether commingling of scripts is allowed
	 */
	private Boolean commingleAllowed = Boolean.FALSE;

	/**
	 * Character encoding for transforming Unicode characters uniquely and
	 * reversibly into DNS compatible characters
	 */
	private String encoding = "Punycode";

	/**
	 * {@code List} of {@link EPPRegistryLanguage} that defines the supported
	 * language codes and character code point policy
	 */
	private List<EPPRegistryLanguage> languages = new ArrayList<EPPRegistryLanguage>();

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

		Element root = aDocument.createElementNS(EPPRegistryMapFactory.NS, ELM_NAME);

		// IDN Version
		if (this.idnVersion != null && this.idnVersion.trim().length() > 0) {
			EPPUtil.encodeString(aDocument, root, this.idnVersion, EPPRegistryMapFactory.NS,
			      EPPRegistryMapFactory.NS_PREFIX + ":" + ELM_IDN_VERSION);
		}

		// IDNA Version
		EPPUtil.encodeString(aDocument, root, this.idnaVersion, EPPRegistryMapFactory.NS,
		      EPPRegistryMapFactory.NS_PREFIX + ":" + ELM_IDNA_VERSION);

		// Unicode Version
		EPPUtil.encodeString(aDocument, root, this.unicodeVersion, EPPRegistryMapFactory.NS,
		      EPPRegistryMapFactory.NS_PREFIX + ":" + ELM_UNICODE_VERSION);

		// Encoding
		if (this.encoding == null && this.encoding.trim().length() == 0) {
			this.encoding = "Punycode";
		}
		EPPUtil.encodeString(aDocument, root, this.encoding, EPPRegistryMapFactory.NS,
		      EPPRegistryMapFactory.NS_PREFIX + ":" + ELM_ENCODING);

		// Commingle Allowed
		if (this.commingleAllowed == null) {
			this.commingleAllowed = Boolean.FALSE;
		}
		EPPUtil.encodeString(aDocument, root, this.commingleAllowed.toString(), EPPRegistryMapFactory.NS,
		      EPPRegistryMapFactory.NS_PREFIX + ":" + ELM_COMMINGLE_ALLOWED);

		// Languages
		if (this.languages != null && this.languages.size() > 0) {
			EPPUtil.encodeCompList(aDocument, root, this.languages);
		}

		return root;
	}

	/**
	 * Decode the {@code EPPRegistryIDN} attributes from the aElement DOM Element
	 * tree.
	 *
	 * @param aElement
	 *           Root DOM Element to decode {@code EPPRegistryIDN} from.
	 *
	 * @exception EPPDecodeException
	 *               Unable to decode aElement
	 */
	@Override
	public void decode(Element aElement) throws EPPDecodeException {
		// IDN Version
		this.idnVersion = EPPUtil.decodeString(aElement, EPPRegistryMapFactory.NS, ELM_IDN_VERSION);
		
		// IDNA Version
		this.idnaVersion = EPPUtil.decodeString(aElement, EPPRegistryMapFactory.NS, ELM_IDNA_VERSION);
		
		// Unicode Version
		this.unicodeVersion = EPPUtil.decodeString(aElement, EPPRegistryMapFactory.NS, ELM_UNICODE_VERSION);

		// Encoding
		this.encoding = EPPUtil.decodeString(aElement, EPPRegistryMapFactory.NS, ELM_ENCODING);
		if (this.encoding == null && this.encoding.trim().length() == 0) {
			this.encoding = "Punycode";
		}
		
		// Commingle Allowed
		this.commingleAllowed = EPPUtil.decodeBoolean(aElement, EPPRegistryMapFactory.NS, ELM_COMMINGLE_ALLOWED);
		if (this.commingleAllowed == null) {
			this.commingleAllowed = Boolean.FALSE;
		}
		
		// Languages
		this.languages = EPPUtil.decodeCompList(aElement, EPPRegistryMapFactory.NS, EPPRegistryLanguage.ELM_NAME,
		      EPPRegistryLanguage.class);
	}

	/**
	 * Validate the state of the {@code EPPRegistryIDN} instance. A valid state
	 * means that all of the required attributes have been set. If validateState
	 * returns without an exception, the state is valid. If the state is not
	 * valid, the EPPCodecException will contain a description of the error.
	 * throws EPPCodecException State error. This will contain the name of the
	 * attribute that is not valid.
	 *
	 * @throws EPPCodecException
	 */
	void validateState() throws EPPCodecException {
		if (this.unicodeVersion == null || this.unicodeVersion.trim().length() == 0) {
			throw new EPPCodecException("unicodeVersion element is not set");
		}
		if (this.idnaVersion == null || this.idnaVersion.trim().length() == 0) {
			throw new EPPCodecException("idnaVersion element is not set");
		}

	}

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

		if (this.languages != null) {
			clone.languages = (List<EPPRegistryLanguage>) ((ArrayList<EPPRegistryLanguage>) this.languages)
			      .clone();
		}

		return clone;
	}

	/**
	 * implements a deep {@code EPPRegistryIDN} compare.
	 *
	 * @param aObject
	 *           {@code EPPRegistryIDN} 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 EPPRegistryIDN)) {
			return false;
		}

		EPPRegistryIDN theComp = (EPPRegistryIDN) aObject;

		// IDN Version
		if (!EqualityUtil.equals(this.idnVersion, theComp.idnVersion)) {
			cat.error("EPPRegistryIDN.equals(): idnVersion not equal");
			return false;
		}
		
		// IDNA Version
		if (!EqualityUtil.equals(this.idnaVersion, theComp.idnaVersion)) {
			cat.error("EPPRegistryIDN.equals(): idnaVersion not equal");
			return false;
		}
		
		// Unicode Version
		if (!EqualityUtil.equals(this.unicodeVersion, theComp.unicodeVersion)) {
			cat.error("EPPRegistryIDN.equals(): unicodeVersion not equal");
			return false;
		}
		
		// Encoding
		if (!EqualityUtil.equals(this.encoding, theComp.encoding)) {
			cat.error("EPPRegistryIDN.equals(): encoding not equal");
			return false;
		}
		
		// Commingle Allowed
		if (!EqualityUtil.equals(this.commingleAllowed, theComp.commingleAllowed)) {
			cat.error("EPPRegistryIDN.equals(): commingleAllowed not equal");
			return false;
		}

		// Languages
		if (!((this.languages == null) ? (theComp.languages == null)
		      : EPPUtil.equalLists(this.languages, theComp.languages))) {
			cat.error("EPPRegistryIDN.equals(): languages 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 idnVersion.
	 *
	 * @return {@code String} representation of idnVersion
	 */
	public String getIdnVersion() {
		return this.idnVersion;
	}

	/**
	 * Sets the idnVersion.
	 *
	 * @param aIdnVersion
	 *           {@code String} representation of idnVersion
	 */
	public void setIdnVersion(String aIdnVersion) {
		this.idnVersion = aIdnVersion;
	}

	/**
	 * Gets the unicodeVersion.
	 *
	 * @return {@code String} representation of unicodeVersion
	 */
	public String getUnicodeVersion() {
		return this.unicodeVersion;
	}

	/**
	 * Sets the unicodeVersion.
	 *
	 * @param aUnicodeVersion
	 *           {@code String} representation of unicodeVersion
	 */
	public void setUnicodeVersion(String aUnicodeVersion) {
		this.unicodeVersion = aUnicodeVersion;
	}

	/**
	 * Gets the idnaVersion.
	 *
	 * @return {@code String} representation of idnaVersion
	 */
	public String getIdnaVersion() {
		return this.idnaVersion;
	}

	/**
	 * Sets the idnaVersion.
	 *
	 * @param aIdnaVersion
	 *           {@code String} representation of idnaVersion
	 */
	public void setIdnaVersion(String aIdnaVersion) {
		this.idnaVersion = aIdnaVersion;
	}

	/**
	 * Gets the character encoding.
	 *
	 * @return character encoding for transforming Unicode characters uniquely
	 *         and reversibly into DNS compatible characters
	 */
	public String getEncoding() {
		return this.encoding;
	}

	/**
	 * Sets the character encoding.
	 *
	 * @param aEncoding
	 *           character encoding for transforming Unicode characters uniquely
	 *           and reversibly into DNS compatible characters
	 */
	public void setEncoding(String aEncoding) {
		this.encoding = aEncoding;
	}

	/**
	 * Gets whether commingling of scripts is allowed.
	 *
	 * @return {@code true} allow commingling; {@code false} do not allow
	 *         commingling
	 */
	public Boolean getCommingleAllowed() {
		return this.commingleAllowed;
	}

	/**
	 * Sets whether commingling of scripts is allowed.
	 *
	 * @param aCommingleAllowed
	 *           {@code true} allow commingling; {@code false} do not allow
	 *           commingling
	 */
	public void setCommingleAllowed(Boolean aCommingleAllowed) {
		this.commingleAllowed = aCommingleAllowed;
	}

	/**
	 * Gets the {@code List} of {@link EPPRegistryLanguage}.
	 *
	 * @return {@code List} of {@link EPPRegistryLanguage} that defines the
	 *         supported language codes and character code point policy
	 */
	public List<EPPRegistryLanguage> getLanguages() {
		return this.languages;
	}

	/**
	 * Sets the {@code List} of {@link EPPRegistryLanguage}.
	 *
	 * @param aLanguages
	 *           {@code List} of {@link EPPRegistryLanguage} that defines the
	 *           supported language codes and character code point policy
	 */
	public void setLanguages(List<EPPRegistryLanguage> aLanguages) {
		this.languages = aLanguages;
	}

	/**
	 * Append one instance of {@link EPPRegistryLanguage} to the existing
	 * list.
	 *
	 * @param language
	 *           instance of {@link EPPRegistryLanguage} that defines the
	 *           supported language codes and character code point policy
	 */
	public void addLanguage(EPPRegistryLanguage language) {
		if (this.languages == null) {
			this.languages = new ArrayList();
		}
		this.languages.add(language);
	}

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

}
