/***********************************************************
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.EqualityUtil;

/**
 * Defines the supported registration periods and default periods by command
 * type. The required "command" attribute defines the command type with sample
 * values of "create", "renew", and "transfer". The &lt;registry:period&gt;
 * element contains ONE of the following elements: <br>
 * <br>
 * <ul>
 * <li>&lt;registry:length&gt; - The default, minimum, and maximum period length
 * for the command type. Use {@link #getLength()} and
 * {@link #setLength(EPPRegistryMinMaxPeriod)} to get and set this element.</li>
 * <li>&lt;registry:serverDecided&gt; - The registration period is decided by
 * the server based on the relationship to a related object that MUST have the
 * same expiration date. Use {@link #getServerDecided()} and
 * {@link #setServerDecided(Boolean)} to get and set this element.</li>
 * </ul>
 *
 * @see com.verisign.epp.codec.registry.v02.EPPRegistryDomain
 * @see com.verisign.epp.codec.registry.v02.EPPRegistryMinMaxPeriod
 */
public class EPPRegistryDomainPeriod implements EPPCodecComponent {

  /**
   * Logger
   */
      private static Logger cat = LoggerFactory.getLogger(EPPRegistryDomainPeriod.class);
        

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

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

  /**
   * XML Element Name of <code>serverDecided</code> attribute.
   */
  public static final String ELM_SERVER_DECIDED = "serverDecided";

  /**
   * XML attribute name for the <code>command</code> attribute.
   */
  public static final String ATTR_COMMAND = "command";

  /**
   * Maximum period in years as defined in RFC5731
   */
  public static final int MAX_PERIOD = 99;

  /**
   * Maximum period in years as defined in RFC5731
   */
  public static final int MIN_PERIOD = 1;

  /**
   * Instance of {@link EPPRegistryMinMaxPeriod} that defines min/max/default
   * period for a given command. If this attribute is not {@code null}, then
   * "serverDecided" attribute must be {@code false}, and vice versa.
   */
  private EPPRegistryMinMaxPeriod length = null;

  /**
   * Whether no not to have server decided expiration date. If this is set to
   * {@code true}, then "length" attribute must be set to null, and vice verse.
   */
  private Boolean serverDecided = Boolean.FALSE;

  /**
   * Command type. Valid values are "create", "renew" or "transfer".
   */
  private String command = null;

  /**
   * Default constructor. Attributes are set default values:
   * <ul>
   * <li>{@code command} - {@code null}</li>
   * <li>{@code length} - {@code null}</li>
   * <li>{@code serverDecided} - {@code Boolean.FALSE}</li>
   * </ul>
   */
  public EPPRegistryDomainPeriod() {
  }

  /**
   * Construct an instance of {@code EPPRegistryDomainPeriod} with the
   * following inputs. {@code serverDecided} is set to {@code Boolean.FALSE}:
   *
   * @param aCommand
   *           command type
   * @param aMin
   *           minimum length number
   * @param aMinUnit
   *           minimum length unit
   * @param aMax
   *           maximum length number
   * @param aMaxUnit
   *           maximum length unit
   * @param aDefaultLength
   *           default length number
   * @param aDefaultLengthUnit
   *           length unit
   */
  public EPPRegistryDomainPeriod(String aCommand, Integer aMin, EPPRegistryPeriodType.Unit aMinUnit, Integer aMax,
        EPPRegistryPeriodType.Unit aMaxUnit, Integer aDefaultLength, EPPRegistryPeriodType.Unit aDefaultLengthUnit) {
    this.command = aCommand;
    this.length = new EPPRegistryMinMaxPeriod(aMin, aMinUnit, aMax, aMaxUnit, aDefaultLength, aDefaultLengthUnit);
  }

  /**
   * Construct an instance of {@code EPPRegistryDomainPeriod} with the
   * following inputs. {@code serverDecided} is set to {@code Boolean.FALSE}:
   *
   * @param aCommand
   *           command type
   * @param aMin
   *           minimum length number
   * @param aMinUnit
   *           minimum length unit
   * @param aMax
   *           maximum length number
   * @param aMaxUnit
   *           maximum length unit
   * @param aDefaultLength
   *           default length number
   * @param aDefaultLengthUnit
   *           length unit
   */
  public EPPRegistryDomainPeriod(String aCommand, int aMin, EPPRegistryPeriodType.Unit aMinUnit, int aMax,
        EPPRegistryPeriodType.Unit aMaxUnit, int aDefaultLength, EPPRegistryPeriodType.Unit aDefaultLengthUnit) {
    this.command = aCommand;
    this.length = new EPPRegistryMinMaxPeriod(aMin, aMinUnit, aMax, aMaxUnit, aDefaultLength, aDefaultLengthUnit);
  }

  /**
   * Construct an instance of {@code EPPRegistryDomainPeriod} with the
   * following inputs. {@code length} is set to {@code null}:
   *
   * @param aCommand
   *           command type
   * @param aServerDecided
   *           whether no not to have server decided expiration date
   */
  public EPPRegistryDomainPeriod(String aCommand, Boolean aServerDecided) {
    this.command = aCommand;
    this.serverDecided = aServerDecided;
  }

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

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

    // Command
    root.setAttribute(ATTR_COMMAND, this.command);

    // Length
    if (this.length != null) {
      EPPUtil.encodeComp(aDocument, root, this.length);
    }

    // Server Decided
    if (this.serverDecided.booleanValue()) {
      Element child = aDocument.createElementNS(EPPRegistryMapFactory.NS,
            EPPRegistryMapFactory.NS_PREFIX + ":" + ELM_SERVER_DECIDED);
      root.appendChild(child);
    }

    return root;
  }

  /**
   * Decode the {@code EPPRegistryDomainPeriod} attributes from the aElement
   * DOM Element tree.
   *
   * @param aElement
   *           Root DOM Element to decode {@code EPPRegistryDomainPeriod} from.
   *
   * @exception EPPDecodeException
   *               Unable to decode aElement
   */
  @Override
  public void decode(Element aElement) throws EPPDecodeException {
    // Command
    this.command = aElement.getAttribute(ATTR_COMMAND);

    // Server Decided
    Element child = EPPUtil.getElementByTagNameNS(aElement, EPPRegistryMapFactory.NS, ELM_SERVER_DECIDED);
    this.serverDecided = (child == null) ? Boolean.FALSE : Boolean.TRUE;
    if (Boolean.FALSE == this.serverDecided) {
      this.setLength((EPPRegistryMinMaxPeriod) EPPUtil.decodeComp(aElement, EPPRegistryMapFactory.NS,
            EPPRegistryMinMaxPeriod.ELM_NAME, EPPRegistryMinMaxPeriod.class));
    }
  }

  /**
   * Validate the state of the <code>EPPRegistryDomainPeriod</code> 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
   *            Validation error
   */
  void validateState() throws EPPCodecException {
    if ((this.length == null && !this.serverDecided.booleanValue())
          || (this.length != null && this.serverDecided.booleanValue())) {
      throw new EPPCodecException("Either specify length or make it server decided");
    }

    // Command
    if (this.command == null || this.command.trim().length() == 0) {
      throw new EPPEncodeException("command is required");
    }

    // Length
    if (this.length != null) {
      validPeriod(this.length.getMin(), "min");
      validPeriod(this.length.getMax(), "max");
      validPeriod(this.length.getDefaultLength(), "default");
      if (comparePeriod(this.length.getMin(), this.length.getDefaultLength()) > 0) {
        throw new EPPCodecException("min period cannot be greater than default period");
      }
      if (comparePeriod(this.length.getDefaultLength(), this.length.getMax()) > 0) {
        throw new EPPCodecException("default period cannot be greater than max period");
      }
    }
  }

  /**
   * Validate a {@link EPPRegistryPeriodType}, which applies to the {@code min}
   * , {@code max}, and {@code default} length attributes.
   * 
   * @param aPeriod
   *           Either the {@code min}, {@code max}, and {@code default} length
   *           attributes.
   * @param aType
   *           The type string that helps identify which {@code min},
   *           {@code max}, and {@code default} is passed.
   * @throws EPPCodecException
   *            Validation error
   */
  private void validPeriod(EPPRegistryPeriodType aPeriod, String aType) throws EPPCodecException {
    if (aPeriod == null) {
      throw new EPPCodecException(aType + " period is required");
    }
    aPeriod.validateState();
  }

  /**
   * Compare two periods
   * 
   * @param aLeft
   *           Left period to compare
   * @param aRight
   *           Right period to compare
   * @return {@code 0} if {@code aLeft} and {@code aRight} are equal, negative
   *         if {@code aLeft} is greater than {@code aRight}, and positive if
   *         {@code aRight} is greater than {@code aLeft}.
   */
  private int comparePeriod(EPPRegistryPeriodType aLeft, EPPRegistryPeriodType aRight) {
    int l = 0;
    int r = 0;
    if ("y".equals(aLeft.getUnit())) {
      l = aLeft.getNumber().intValue() * 12;
    }
    else if ("m".equals(aLeft.getUnit())) {
      l = aLeft.getNumber().intValue();
    }
    if ("y".equals(aRight.getUnit())) {
      r = aRight.getNumber().intValue() * 12;
    }
    else if ("m".equals(aRight.getUnit())) {
      r = aRight.getNumber().intValue();
    }

    return l - r;
  }

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

    // Length
    if (this.length != null) {
      clone.length = (EPPRegistryMinMaxPeriod) this.length.clone();
    }

    return clone;
  }

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

    EPPRegistryDomainPeriod theComp = (EPPRegistryDomainPeriod) aObject;

    // Length
    if (!EqualityUtil.equals(this.length, theComp.length)) {
      cat.error("EPPRegistryDomainPeriod.equals(): length not equal");
      return false;
    }

    // Server Decided
    if (!EqualityUtil.equals(this.serverDecided, theComp.serverDecided)) {
      cat.error("EPPRegistryDomainPeriod.equals(): serverDecided not equal");
      return false;
    }

    // Command
    if (!EqualityUtil.equals(this.command, theComp.command)) {
      cat.error("EPPRegistryDomainPeriod.equals(): command not equal");
      return false;
    }

    return true;
  }

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

  /**
   * Gets the length for an EPP domain transform command.
   *
   * @return instance of {@link EPPRegistryMinMaxPeriod} that defines
   *         min/max/default period for a given command
   */
  public EPPRegistryMinMaxPeriod getLength() {
    return this.length;
  }

  /**
   * Sets the length for an EPP domain transform command.
   *
   * @param length
   *           instance of {@link EPPRegistryMinMaxPeriod} that defines
   *           min/max/default period for a given command
   */
  public void setLength(EPPRegistryMinMaxPeriod length) {
    this.length = length;
  }

  /**
   * Gets whether to have server decided expiration date.
   *
   * @return {@code true} - the registration period is decided by the server
   *         based on the relationship to a related object that MUST have the
   *         same expiration date. {@code false} - the registration period is
   *         specified in the {@code length} attribute.
   */
  public Boolean getServerDecided() {
    return this.serverDecided;
  }

  /**
   * Sets whether to have server decided expiration date.
   *
   * @param serverDecided
   *           {@code true} - the registration period is decided by the server
   *           based on the relationship to a related object that MUST have the
   *           same expiration date. {@code false} - the registration period is
   *           specified in the {@code length} attribute.
   */
  public void setServerDecided(Boolean serverDecided) {
    this.serverDecided = serverDecided;
  }

  /**
   * Gets the command type.
   *
   * @return command type in {@code String}. Valid values are "create", "renew"
   *         and "transfer".
   */
  public String getCommand() {
    return this.command;
  }

  /**
   * Sets the command type.
   *
   * @param command
   *           command type in {@code String}. Valid values are "create",
   *           "renew" and "transfer".
   */
  public void setCommand(String command) {
    this.command = command;
  }

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

}
