/***********************************************************
 Copyright (C) 2017 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.rootzone.interfaces;

import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.verisign.epp.codec.gen.EPPResponse;
import com.verisign.epp.codec.gen.EPPResult;
import com.verisign.epp.interfaces.EPPApplicationSingle;
import com.verisign.epp.interfaces.EPPCommandException;
import com.verisign.epp.interfaces.EPPSession;
import com.verisign.epp.pool.EPPSessionPool;
import com.verisign.epp.util.InvalidateSessionException;
import com.verisign.epp.util.TestThread;
import com.verisign.epp.util.TestUtil;

import junit.extensions.TestSetup;
import junit.framework.Assert;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Test of the use of the {@code RZHost} interface. This test utilizes
 * the EPP session pool and exercises all of the operations defined in
 * {@code RZHost} and the base class {@code EPPHost}.
 * 
 * @see com.verisign.epp.rootzone.interfaces.RZHost
 * @see com.verisign.epp.interfaces.EPPHost
 */
public class RZHostTst extends TestCase {

	/**
	 * Handle to the Singleton EPP Application instance (
	 * {@code EPPApplicationSingle})
	 */
	private static EPPApplicationSingle app = EPPApplicationSingle.getInstance();

	/** Name of configuration file to use for test (default = epp.config). */
	private static String configFileName = "epp.rootzone.config";

	/** Logging category */
	private static Logger cat = LoggerFactory.getLogger(RZHostTst.class);
	      

	/** EPP Session pool associated with test */
	private static EPPSessionPool sessionPool = null;

	/**
	 * Random instance for the generation of unique objects (hosts, IP addresses,
	 * etc.).
	 */
	private Random rd = new Random(System.currentTimeMillis());

	/**
	 * Allocates an {@code NSDomainTst} with a logical name. The constructor
	 * will initialize the base class {@code TestCase} with the logical
	 * name.
	 * 
	 * @param name
	 *           Logical name of the test
	 */
	public RZHostTst(String name) {
		super(name);
	}

	/**
	 * Unit test of {@code RZHost.sendUpdate} with change request extension
	 * command.
	 */
	public void testHostUpdate() {
		printStart("testHostUpdate");

		EPPSession theSession = null;
		EPPResponse theResponse = null;

		try {
			theSession = this.borrowSession();
			RZHost theHost = new RZHost(theSession);

			try {
				System.out.println("\n----------------------------------------------------------------");

				String theHostName = this.makeDomainName();

				System.out.println("hostUpdate: Update " + theHostName + " with no optional attributes");

				theHost.setTransId("ABC-12345-XYZ");

				theHost.addHostName(theHostName);

				theHost.addIPV4Address(this.makeIP());
				
				theResponse = theHost.sendUpdate("thx1138");

				// -- Output all of the response attributes
				System.out.println("hostUpdate: Response = [" + theResponse + "]\n\n");

			}
			catch (Exception ex) {
				TestUtil.handleException(theSession, ex);
			}

		}
		catch (InvalidateSessionException ex) {
			this.invalidateSession(theSession);
			theSession = null;
		}
		finally {
			if (theSession != null)
				this.returnSession(theSession);
		}

		printEnd("testHostUpdate");
	}

	/**
	 * JUNIT {@code setUp} method
	 */
	protected void setUp() {

	}

	// End NSDomainTst.setUp();

	/**
	 * JUNIT {@code tearDown}, which currently does nothing.
	 */
	protected void tearDown() {
	}

	// End NSDomainTst.tearDown();

	/**
	 * JUNIT {@code suite} static method, which returns the tests associated
	 * with {@code NSDomainTst}.
	 * 
	 * @return DOCUMENT ME!
	 */
	public static Test suite() {
		return new RZHostTstSetup(new TestSuite(RZHostTst.class));
	}

	// End NSDomainTst.suite()

	/**
	 * Setup framework from running NSDomainTst tests.
	 */
	private static class RZHostTstSetup extends TestSetup {

		/**
		 * Creates setup instance for passed in tests.
		 * 
		 * @param aTest
		 *           Tests to execute
		 */
		public RZHostTstSetup(Test aTest) {
			super(aTest);
		}

		/**
		 * Setup framework for running NSDomainTst tests.
		 */
		protected void setUp() throws Exception {
			super.setUp();

			String theConfigFileName = System.getProperty("EPP.ConfigFile");
			if (theConfigFileName != null)
				configFileName = theConfigFileName;

			try {
				app.initialize(configFileName);
			}
			catch (EPPCommandException e) {
				e.printStackTrace();
				Assert.fail("Error initializing the EPP Application: " + e);
			}

			// Initialize the session pool
			try {
				sessionPool = EPPSessionPool.getInstance();
				sessionPool.init();
			}
			catch (Exception ex) {
				ex.printStackTrace();
				Assert.fail("Error initializing the session pool: " + ex);
			}

		}

		/**
		 * Tear down framework from running NSDomainTst tests.
		 */
		protected void tearDown() throws Exception {
			super.tearDown();
		}
	}

	/**
	 * Unit test main, which accepts the following system property options: <br>
	 * <ul>
	 * <li>iterations Number of unit test iterations to run</li>
	 * <li>validate Turn XML validation on ({@code true}) or off (
	 * {@code false}). If validate is not specified, validation will be off.
	 * </li>
	 * </ul>
	 * 
	 * @param args
	 *           DOCUMENT ME!
	 */
	public static void main(String[] args) {
		// Override the default configuration file name?
		if (args.length > 0) {
			configFileName = args[0];
		}

		// Number of Threads
		int numThreads = 1;
		String threadsStr = System.getProperty("threads");

		if (threadsStr != null) {
			numThreads = Integer.parseInt(threadsStr);
		}

		// Run test suite in multiple threads?
		if (numThreads > 1) {
			// Spawn each thread passing in the Test Suite
			for (int i = 0; i < numThreads; i++) {
				TestThread thread = new TestThread("NSDomainTst Thread " + i, RZHostTst.suite());
				thread.start();
			}
		}
		else { // Single threaded mode.
			junit.textui.TestRunner.run(RZHostTst.suite());
		}

		try {
			app.endApplication();
		}
		catch (EPPCommandException e) {
			e.printStackTrace();
			Assert.fail("Error ending the EPP Application: " + e);
		}
	}

	// End NSDomainTst.main(String [])

	/**
	 * Print the start of a test with the {@code Thread} name if the current
	 * thread is a {@code TestThread}.
	 * 
	 * @param aTest
	 *           name for the test
	 */
	public static void printStart(String aTest) {
		if (Thread.currentThread() instanceof TestThread) {
			System.out.print(Thread.currentThread().getName() + ": ");
			cat.info(Thread.currentThread().getName() + ": " + aTest + " Start");
		}

		System.out.println("Start of " + aTest);
		System.out.println("****************************************************************\n");
	}

	// End NSDomainTst.testStart(String)

	/**
	 * Print the end of a test with the {@code Thread} name if the current
	 * thread is a {@code TestThread}.
	 * 
	 * @param aTest
	 *           name for the test
	 */
	public static void printEnd(String aTest) {
		System.out.println("****************************************************************");

		if (Thread.currentThread() instanceof TestThread) {
			System.out.print(Thread.currentThread().getName() + ": ");
			cat.info(Thread.currentThread().getName() + ": " + aTest + " End");
		}

		System.out.println("End of " + aTest);
		System.out.println("\n");
	}

	// End NSDomainTst.testEnd(String)

	/**
	 * Utility method to borrow a session from the session pool. All exceptions
	 * will result in the test failing. This method should only be used for
	 * positive session pool tests.
	 * 
	 * @return Session from the session pool
	 */
	private EPPSession borrowSession() {
		EPPSession theSession = null;
		try {
			theSession = sessionPool.borrowObject();
		}
		catch (Exception ex) {
			ex.printStackTrace();
			Assert.fail("borrowSession(): Exception borrowing session: " + ex);
		}

		return theSession;
	}

	/**
	 * Utility method to return a session to the session pool. This should be
	 * placed in a finally block. All exceptions will result in the test failing.
	 * 
	 * @param aSession
	 *           Session to return to the pool
	 */
	private void returnSession(EPPSession aSession) {
		try {
			if (aSession != null)
				sessionPool.returnObject(aSession);
		}
		catch (Exception ex) {
			ex.printStackTrace();
			Assert.fail("returnSession(): Exception returning session: " + ex);
		}
	}

	/**
	 * Utility method to invalidate a session in the session pool. This should be
	 * placed in an exception block.
	 * 
	 * @param aSession
	 *           Session to invalidate in the pool
	 */
	private void invalidateSession(EPPSession aSession) {
		try {
			if (aSession != null)
				sessionPool.invalidateObject(aSession);
		}
		catch (Exception ex) {
			ex.printStackTrace();
			Assert.fail("invalidateSession(): Exception invalidating session: " + ex);
		}
	}

	/**
	 * Handle a response by printing out the result details.
	 * 
	 * @param aResponse
	 *           the response to handle
	 */
	private void handleResponse(EPPResponse aResponse) {

		for (int i = 0; i < aResponse.getResults().size(); i++) {
			EPPResult theResult = (EPPResult) aResponse.getResults().elementAt(i);

			System.out.println("Result Code    : " + theResult.getCode());
			System.out.println("Result Message : " + theResult.getMessage());
			System.out.println("Result Lang    : " + theResult.getLang());

			if (theResult.isSuccess()) {
				System.out.println("Command Passed ");
			}
			else {
				System.out.println("Command Failed ");
			}

			if (theResult.getAllValues() != null) {
				for (int k = 0; k < theResult.getAllValues().size(); k++) {
					System.out.println("Result Values  : " + theResult.getAllValues().elementAt(k));
				}
			}
		}
	} // End handleResponse(EPPResponse)

	/**
	 * This method tries to generate a unique String as Domain Name and Name
	 * Server
	 * 
	 * @return Unique domain name
	 */
	public String makeDomainName() {
		long tm = System.currentTimeMillis();

		return new String(Thread.currentThread() + String.valueOf(tm + rd.nextInt(12)).substring(10) + ".com");
	}

	/**
	 * Makes a unique IP address based off of the current time.
	 * 
	 * @return Unique IP address {@code String}
	 */
	public String makeIP() {
		long tm = System.currentTimeMillis();

		return new String(
		      String.valueOf(tm + rd.nextInt(50)).substring(10) + "." + String.valueOf(tm + rd.nextInt(50)).substring(10)
		            + "." + String.valueOf(tm + rd.nextInt(50)).substring(10) + "."
		            + String.valueOf(tm + rd.nextInt(50)).substring(10));
	}

	/**
	 * Makes a unique host name for a domain using the current time.
	 * 
	 * @param newDomainName
	 *           DOCUMENT ME!
	 * @return Unique host name {@code String}
	 */
	public String makeHostName(String newDomainName) {
		long tm = System.currentTimeMillis();

		return new String(String.valueOf(tm + rd.nextInt(10)).substring(10) + "." + newDomainName);
	}

	/**
	 * Makes a unique contact name using the current time.
	 * 
	 * @return Unique contact name {@code String}
	 */
	public String makeContactName() {
		long tm = System.currentTimeMillis();

		return new String("Con" + String.valueOf(tm + rd.nextInt(5)).substring(7));
	}

}
