/***********************************************************
 Copyright (C) 2004 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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.verisign.epp.codec.domain.EPPDomainMapFactory;
import com.verisign.epp.codec.gen.EPPFactory;
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.EPPChange;
import com.verisign.epp.interfaces.EPPCommandException;
import com.verisign.epp.interfaces.EPPDomain;
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 RZDomain} and {@code EPPChange}
 * interfaces. This test utilizes the EPP session pool and exercises some of the
 * operations defined in {@code RZDomain} and {@code EPPChange}.
 * @see com.verisign.epp.rootzone.interfaces.RZDomain
 * @see com.verisign.epp.interfaces.EPPDomain
 * @see com.verisign.epp.interfaces.EPPChange
 */
public class RZExampleTst 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(RZExampleTst.class);
			

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

	static private final String VSPACE = "\n-----------------------------------------";

	/**
	 * Allocates an {@code RZExampleTst} 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 RZExampleTst(String name) {
		super(name);
	}

	public void test1() {
		printStart("test1");

		String domainname = "test1-domain-thx1138";
		String changerequestid = "test1-changerequest-thx1138";
		String cltrid = "test1-cli-thx1138";

		EPPSession theSession = null;
		EPPResponse theResponse = null;

		try {
			theSession = this.borrowSession();
			EPPChange changeService = new EPPChange(theSession);
			RZDomain domainService = new RZDomain(theSession);

			/**
			 * Create a Change Request
			 */
			try {
				theResponse = changeService.sendCreate(changerequestid, "MUSEUM",
						"test1 description");
				System.out.println("test1.change.create.cmd: "
						+ changeService.getLastCommand());
				System.out.println("test1.change.create.rsp: " + theResponse);

				for (int i = 0; i < theResponse.getResults().size(); i++) {
					EPPResult myResult = (EPPResult) theResponse.getResults()
							.elementAt(i);
					System.out.println("Result Code    : " + myResult.getCode());
					System.out.println("Result Message : " + myResult.getMessage());
					System.out.println("Result Lang    : " + myResult.getLang());
					if (myResult.isSuccess()) {
						System.out.println("Command Passed ");
					} else {
						System.out.println("Command Failed ");
					}
					if (myResult.getValues() != null) {
						for (int k = 0; k < myResult.getValues().size(); k++) {
							System.out.println("Result Values  : "
									+ myResult.getValues().elementAt(k));
						}
					}
				}
			} catch (Exception ex) {
				TestUtil.handleException(theSession, ex);
			}

			/**
			 * Append a domain.create to the ChangeRequest
			 */

			try {
				System.out.println(VSPACE);
				System.out.println("test1.domain.create(" + domainname + ")");
				domainService.setTransId(cltrid);
				domainService.addDomainName(domainname);
				domainService.addHostName("ns1." + domainname);
				domainService.addHostName("ns2." + domainname);
				/**
				 * If the contact mapping is supported, add contacts
				 */
				if (EPPFactory.getInstance().hasService(EPPDomainMapFactory.NS_CONTACT)) {
					domainService.addContact("t1138", EPPDomain.CONTACT_ADMINISTRATIVE);
					domainService.addContact("t1138", EPPDomain.CONTACT_TECHNICAL);
					domainService.addContact("t1138", EPPDomain.CONTACT_BILLING);
				}
				domainService.setPeriodLength(10);
				domainService.setPeriodUnit(EPPDomain.PERIOD_YEAR);
				domainService.setAuthString("ClientX");
				theResponse = domainService.sendCreate(changerequestid);
				System.out.println("domain.create.response: [" + theResponse + "]\n\n");
			} catch (Exception ex) {
				TestUtil.handleException(theSession, ex);
			}

			/**
			 * Info the Change Request
			 */
			try {
				theResponse = changeService.sendInfo(changerequestid);
				System.out.println("test1.change.info.cmd: "
						+ changeService.getLastCommand());
				System.out.println("test1.change.info.rsp: " + theResponse);

				for (int i = 0; i < theResponse.getResults().size(); i++) {
					EPPResult myResult = (EPPResult) theResponse.getResults()
							.elementAt(i);
					System.out.println("Result Code    : " + myResult.getCode());
					System.out.println("Result Message : " + myResult.getMessage());
					System.out.println("Result Lang    : " + myResult.getLang());
					if (myResult.isSuccess()) {
						System.out.println("Command Passed ");
					} else {
						System.out.println("Command Failed ");
					}
					if (myResult.getValues() != null) {
						for (int k = 0; k < myResult.getValues().size(); k++) {
							System.out.println("Result Values  : "
									+ myResult.getValues().elementAt(k));
						}
					}
				}
			} catch (Exception ex) {
				TestUtil.handleException(theSession, ex);
			}

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

		printEnd("test1");
	}

	public void test2() {
		printStart("test2");

		String domainname = "test2-domain-thx1138";
		String changerequestid = "test2-changerequest-thx1138";
		String cltrid = "test2-cli-thx1138";

		EPPSession theSession = null;
		EPPResponse theResponse = null;

		try {
			theSession = this.borrowSession();
			EPPChange changeService = new EPPChange(theSession);
			RZDomain domainService = new RZDomain(theSession);

			/**
			 * Create a Change Request
			 */
			try {
				theResponse = changeService.sendCreate(changerequestid, "URGENT",
						"COM", "test2 description");
				System.out.println("test2.change.create.cmd: "
						+ changeService.getLastCommand());
				System.out.println("test2.change.create.rsp: " + theResponse);

				for (int i = 0; i < theResponse.getResults().size(); i++) {
					EPPResult myResult = (EPPResult) theResponse.getResults()
							.elementAt(i);
					System.out.println("Result Code    : " + myResult.getCode());
					System.out.println("Result Message : " + myResult.getMessage());
					System.out.println("Result Lang    : " + myResult.getLang());
					if (myResult.isSuccess()) {
						System.out.println("Command Passed ");
					} else {
						System.out.println("Command Failed ");
					}
					if (myResult.getValues() != null) {
						for (int k = 0; k < myResult.getValues().size(); k++) {
							System.out.println("Result Values  : "
									+ myResult.getValues().elementAt(k));
						}
					}
				}
			} catch (Exception ex) {
				TestUtil.handleException(theSession, ex);
			}

			/**
			 * Append a domain.create to the ChangeRequest
			 */

			try {
				System.out.println(VSPACE);
				System.out.println("test2.domain.create(" + domainname + ")");
				domainService.setTransId(cltrid);
				domainService.addDomainName(domainname);
				domainService.addHostName("ns1." + domainname);
				domainService.addHostName("ns2." + domainname);
				/**
				 * If the contact mapping is supported, add contacts
				 */
				if (EPPFactory.getInstance().hasService(EPPDomainMapFactory.NS_CONTACT)) {
					domainService.addContact("t1138", EPPDomain.CONTACT_ADMINISTRATIVE);
					domainService.addContact("t1138", EPPDomain.CONTACT_TECHNICAL);
					domainService.addContact("t1138", EPPDomain.CONTACT_BILLING);
				}
				domainService.setPeriodLength(10);
				domainService.setPeriodUnit(EPPDomain.PERIOD_YEAR);
				domainService.setAuthString("ClientX");
				theResponse = domainService.sendCreate(changerequestid);
				System.out.println("domain.create.response: [" + theResponse + "]\n\n");
			} catch (Exception ex) {
				TestUtil.handleException(theSession, ex);
			}

			/**
			 * Info the Change Request
			 */
			try {
				theResponse = changeService.sendInfo(changerequestid);
				System.out.println("test2.change.info.cmd: "
						+ changeService.getLastCommand());
				System.out.println("test2.change.info.rsp: " + theResponse);

				for (int i = 0; i < theResponse.getResults().size(); i++) {
					EPPResult myResult = (EPPResult) theResponse.getResults()
							.elementAt(i);
					System.out.println("Result Code    : " + myResult.getCode());
					System.out.println("Result Message : " + myResult.getMessage());
					System.out.println("Result Lang    : " + myResult.getLang());
					if (myResult.isSuccess()) {
						System.out.println("Command Passed ");
					} else {
						System.out.println("Command Failed ");
					}
					if (myResult.getValues() != null) {
						for (int k = 0; k < myResult.getValues().size(); k++) {
							System.out.println("Result Values  : "
									+ myResult.getValues().elementAt(k));
						}
					}
				}
			} catch (Exception ex) {
				TestUtil.handleException(theSession, ex);
			}

			/**
			 * Submit the Change Request
			 */
			try {
				theResponse = changeService.sendUpdateSubmit(changerequestid);
				System.out.println("test2.change.update.cmd: "
						+ changeService.getLastCommand());
				System.out.println("test2.change.update.rsp: " + theResponse);

				for (int i = 0; i < theResponse.getResults().size(); i++) {
					EPPResult myResult = (EPPResult) theResponse.getResults()
							.elementAt(i);
					System.out.println("Result Code    : " + myResult.getCode());
					System.out.println("Result Message : " + myResult.getMessage());
					System.out.println("Result Lang    : " + myResult.getLang());
					if (myResult.isSuccess()) {
						System.out.println("Command Passed ");
					} else {
						System.out.println("Command Failed ");
					}
					if (myResult.getValues() != null) {
						for (int k = 0; k < myResult.getValues().size(); k++) {
							System.out.println("Result Values  : "
									+ myResult.getValues().elementAt(k));
						}
					}
				}
			} catch (Exception ex) {
				TestUtil.handleException(theSession, ex);
			}

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

		printEnd("test2");
	}

	/**
	 * Unit test of {@code EPPSession.endSession}. One session in the
	 * session pool wil be ended.
	 */
	public void testEndSession() {
		printStart("testEndSession");

		EPPSession theSession = null;
		try {
			theSession = this.borrowSession();
			sessionPool.invalidateObject(theSession);
			theSession = null;
		} catch (Exception ex) {
			ex.printStackTrace();
			Assert.fail("testEndSession(): Exception invalidating session: " + ex);
		} finally {
			if (theSession != null) this.returnSession(theSession);
		}

		printEnd("testEndSession");
	}

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

	}

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

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

	/**
	 * Setup framework from running RZExampleTst tests.
	 */
	private static class RZExampleTstSetup extends TestSetup {

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

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

			String theConfigFileName = System.getProperty("EPP.ConfigFile");
			if (theConfigFileName != null) configFileName = theConfigFileName;
			
			cat.info("config file = " + configFileName);

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

			cat.info("Initialized SDK");

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

		/**
		 * Tear down framework from running RZExampleTst 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("RZExampleTst Thread " + i,
						RZExampleTst.suite());
				thread.start();
			}
		} else { // Single threaded mode.
			junit.textui.TestRunner.run(RZExampleTst.suite());
		}

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

	/**
	 * 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");
	}

	/**
	 * 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");
	}

	/**
	 * 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));
				}
			}
		}
	} 

}
