/***********************************************************
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.v02;

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;

/**
 * Abstract class for defining a period with a number and unit. The root element
 * is defined by the sub-class.
 */
public abstract class EPPRegistryPeriodType implements EPPCodecComponent {

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

	/**
	 * Possible values for the {@code unit} attribute.
	 */
	public static enum Unit {
		/**
		 * Month
		 */
		m,

		/**
		 * Day
		 */
		d,
		/**
		 * Year
		 */
		y,
		/**
		 * Hour
		 */
		h
	}

	/**
	 * Default root element local name
	 */
	public static final String ELM_LOCALNAME = "period";

	/**
	 * Attribute name for the {@code unit} attribute.
	 */
	public static final String ATTR_UNIT = "unit";

	/**
	 * Number of the period
	 */
	protected Integer number = null;

	/**
	 * Unit of the period
	 */
	protected Unit unit = null;

	/**
	 * Default constructor for {@code EPPRegistryPeriodType}. The {@code number}
	 * and {@code unit} attributes must be set.
	 */
	public EPPRegistryPeriodType() {
	}

	/**
	 * {@code EPPRegistryPeriodType} constructor that takes both the period
	 * number as an {@code Integer} and unit.
	 * 
	 * @param aNumber
	 *           Period number
	 * @param aUnit
	 *           Period unit
	 */
	public EPPRegistryPeriodType(Integer aNumber, Unit aUnit) {
		this.number = aNumber;
		this.unit = aUnit;
	}

	/**
	 * {@code EPPRegistryPeriodType} constructor that takes both the period
	 * number as an {@code int} and unit.
	 * 
	 * @param aNumber
	 *           Period number
	 * @param aUnit
	 *           Period unit
	 */
	public EPPRegistryPeriodType(int aNumber, Unit aUnit) {
		this.number = Integer.valueOf(aNumber);
		this.unit = aUnit;
	}

	/**
	 * Gets the root element local name.
	 * 
	 * @return Root element local name.
	 */
	protected String getRootName() {
		return ELM_LOCALNAME;
	}

	/**
	 * Encode a DOM Element tree from the attributes of the
	 * {@code EPPRegistryPeriodType} instance.
	 *
	 * @param aDocument
	 *           DOM Document that is being built. Used as an Element factory.
	 *
	 * @return Element Root DOM Element representing the
	 *         {@code EPPRegistryPeriodType} instance.
	 *
	 * @exception EPPEncodeException
	 *               - Unable to encode {@code EPPRegistryPeriodType} 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,
		      EPPRegistryMapFactory.NS_PREFIX + ":" + getRootName());
		Text currVal = aDocument.createTextNode(String.valueOf(this.number));
		root.setAttribute(ATTR_UNIT, this.unit.toString());
		root.appendChild(currVal);

		return root;
	}

	/**
	 * Decode the {@code EPPRegistryPeriodType} attributes from the aElement DOM
	 * Element tree.
	 *
	 * @param aElement
	 *           Root DOM Element to decode {@code EPPRegistryPeriodType} from.
	 *
	 * @exception EPPDecodeException
	 *               Unable to decode aElement
	 */
	@Override
	public void decode(Element aElement) throws EPPDecodeException {
		// Number
		String theNumStr = EPPUtil.decodeStringValue(aElement);
		try {
			this.number = Integer.valueOf(theNumStr);
		}
		catch (NumberFormatException e) {
			throw new EPPDecodeException("Can't convert value to Integer: " + theNumStr + e);
		}

		// Unit
		String theUnitStr = aElement.getAttribute(ATTR_UNIT);
		if (theUnitStr == null) {
			throw new EPPDecodeException("Could not find the " + ATTR_UNIT + " attribute");
		}
		this.unit = Unit.valueOf(theUnitStr);
	}

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

		EPPRegistryPeriodType theComp = (EPPRegistryPeriodType) aObject;

		// Number
		if (!EqualityUtil.equals(this.number, theComp.number)) {
			cat.error("EPPRegistryPeriodType.equals(): number not equal");
			return false;
		}

		if (!EqualityUtil.equals(this.unit, theComp.unit)) {
			cat.error("EPPRegistryPeriodType.equals(): unit not equal");
			return false;
		}

		return true;
	}

	/**
	 * Validates the state of the {@code EPPRegistryPeriodType}, which must have
	 * both the {@code number} and {@code unit} set.
	 * 
	 * @throws EPPCodecException
	 *            {@code EPPRegistryPeriodType} state is invalid
	 */
	void validateState() throws EPPCodecException {
		if (this.number == null) {
			throw new EPPCodecException(getRootName() + ": number must not be null");
		}
		if (this.unit == null) {
			throw new EPPCodecException(getRootName() + ": unit must not be null");
		}

		// Execute sub-class {@code extraValidation}.
		extraValidate();
	}

	/**
	 * Child class must implement this method for extra validation according to
	 * the mapping document.
	 *
	 * @throws EPPCodecException
	 *            State is invalid
	 */
	abstract void extraValidate() throws EPPCodecException;

	/**
	 * Clone {@code EPPRegistryPeriodType}.
	 *
	 * @return clone of {@code EPPRegistryPeriodType}
	 *
	 * @exception CloneNotSupportedException
	 *               standard Object.clone exception
	 */
	@Override
	public Object clone() throws CloneNotSupportedException {
		return super.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 period number.
	 * 
	 * @return Period number if defined; {@code null} otherwise.
	 */
	public Integer getNumber() {
		return this.number;
	}

	/**
	 * Sets the period number.
	 * 
	 * @param aNumber
	 *           Period number
	 */
	public void setNumber(Integer aNumber) {
		this.number = aNumber;
	}

	/**
	 * Gets the period unit.
	 * 
	 * @return Period unit if defined; {@code null} otherwise.
	 */
	public Unit getUnit() {
		return this.unit;
	}

	/**
	 * Sets the period unit.
	 * 
	 * @param aUnit
	 *           Period unit
	 */
	public void setUnit(Unit aUnit) {
		this.unit = aUnit;
	}
}
