/**
 * Copyright (c) 2004 Red Hat, Inc. All rights reserved.
 *
 * 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 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
 *
 * Component of: Red Hat Application Server
 *
 *
 * Initial Developer:  Vivek Lakshmanan
 *
 */
package org.objectweb.jonas.examples.clients.olstore;

import junit.framework.TestSuite;

import org.objectweb.jonas.examples.util.JExampleTestCase;

import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.TableCell;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;
import com.meterware.httpunit.WebLink;
import java.util.Date;

/**
 * Define a class to test the olstore example.
 * Test authentication and basic operations for the online store.
 * @author Vivek Lakshmanan
 */
public class C_olstore extends JExampleTestCase {

    private Date date;
    /**
     * URL of the login page
     */
    private static final String URL_OLSTORE = "/olstore";

    /**
     * URL of features to test.
     */
    private static final String URL_OLSTORE_POPULATE = "/olstore/populate/Populate.jsp";
    private static final String OLSTORE_ITEM_DETAILS = "Details";
    private static final String OLSTORE_ITEM_ADDTOCART = "Purchase this Item";
    private static final String URL_OLSTORE_ITEM_PURCHASE = "/olstore/checkout/Checkout.do";
    private static final String URL_OLSTORE_LOGOUT = "/olstore/login/Logout.do";
    private static final String URL_OLSTORE_NEWUSER = "/olstore/general/CreateUser.do";

    private static final String URL_OLSTORE_ITEMS = "/olstore/views/index.do";
    /**
     * Main method
     * @param args the arguments
     */
    public static void main(String[] args) {

        String testtorun = null;
        // Get args
        for (int argn = 0; argn < args.length; argn++) {
            String sArg = args[argn];
            if (sArg.equals("-n")) {
                testtorun = args[++argn];
            }
        }
        if (testtorun == null) {
            junit.textui.TestRunner.run(suite());
        } else {
            junit.textui.TestRunner.run(new C_olstore(testtorun));
        }
    }

    /**
     * Get a new TestSuite for this class
     * @return a new TestSuite for this class
     */
    public static TestSuite suite() {
    	return new TestSuite(C_olstore.class);
    }

    /**
     * Setup need for these tests
     * jonasAdmin is required
     * @throws Exception if it fails
     */
    protected void setUp() throws Exception {
        super.setUp();
        useEar("olstore");
	populateDB();
    }


    /**
     * Constructor with a specified name
     * @param s name
     */
    public C_olstore(String s) {
        super(s, URL_OLSTORE_POPULATE);
        date = new Date();
    }

    /**
     * @throws Exception
     */
    private void populateDB() throws Exception{
    	String url = URL_OLSTORE;
    	WebResponse wr = wc.getResponse(getAbsoluteUrl(url));
	if(wr.getText().indexOf("DATABASE POPULATION")!=-1){
		wc.getResponse(getAbsoluteUrl(URL_OLSTORE_POPULATE));
	}
    	/*
    	 *TODO Check for success and failure here
    	 */
    }



   /*
	The test creates a unique username by appending tonas with the last 9 digits of
	the number of milliseconds since epoch till the instantiation of date.
        This should be a fairly unique number but it can potentially be duplicated.
        If an error occurs and you suspect a duplicate entry, try dropping and recreating
	the DB and then re-running the test.
    */

    public void testValidUserCreate() throws Exception{
    	WebResponse wr = wc.getResponse(getAbsoluteUrl(URL_OLSTORE_NEWUSER));
    	WebForm[] forms = wr.getForms();
    	 WebForm form = forms[0];
    	    form.setParameter( "username", "tonas" + getDigitsOfTime());       // (2) check team names
    	    form.setParameter( "passwd1" , "tonas" );
    	    form.setParameter( "passwd2" , "tonas" );
    	    form.setParameter( "fname" , "tonas" );
    	    form.setParameter( "lname" , "tonas" );
    	    form.setParameter( "phoneNum" , "123-456-7890" );
    	    form.setParameter( "emailAdd" , "tonas@test.com" );
    	    form.setParameter( "street1" , "1 tonas st." );
    	    form.setParameter( "city" , "tonas" );
    	    form.setParameter( "province" , "TO" );
    	    form.setParameter( "postalCode" , "12345" );
    	    form.setParameter( "country" , "Tonas" );
    	    wr = form.submit();
    	    if(wr.getText().indexOf("Your Profile has been created")==-1){
		System.out.println(wr.getText());
    	    	fail("Valid User registration did not pass.");
    	    }

    }

   private String getDigitsOfTime(){
	String time = Long.toString(date.getTime());
	return time.substring(time.length()-9);

   }
    public void testInValidUserCreate() throws Exception{
    	WebResponse wr = wc.getResponse(getAbsoluteUrl(URL_OLSTORE_NEWUSER));
    	WebForm[] forms = wr.getForms();
    	 WebForm form = forms[0];
    	    form.setParameter( "username", "ton" );
    	    form.setParameter( "passwd1" , "tonas" );
    	    form.setParameter( "passwd2" , "ton" );
    	    form.setParameter( "fname" , "" );
    	    form.setParameter( "lname" , "" );
    	    form.setParameter( "phoneNum" , "123-AHJ-7890" );
    	    form.setParameter( "emailAdd" , "tonastest.com" );
    	    form.setParameter( "street1" , "1 tonas st." );
    	    form.setParameter( "city" , "tonas" );
    	    form.setParameter( "province" , "TO" );
    	    form.setParameter( "postalCode" , "12345" );
    	    form.setParameter( "country" , "Tonas" );
    	    wr = form.submit();

    	    if(wr.getText().indexOf("Your Profile has been created please click here to login.")!=-1)
    	    	fail("Invalid User registration passed.");
    	    if(wr.getText().indexOf("Confirm Password must match Password")==-1)
    	    	fail("Invalid Username should not have passed registration.");
    	    if(wr.getText().indexOf("Username can not be less than 5 characters.")==-1)
    	    	fail("Invalid Username should not have passed registration.");
    	    if(wr.getText().indexOf("Last Name is required.")==-1)
    	    	fail("Invalid last name should not have passed registration.");
    	    if(wr.getText().indexOf("First Name is required.")==-1)
    	    	fail("Invalid first name should not have passed registration.");
    	    if(wr.getText().indexOf("Email Address is an invalid e-mail address.")==-1)
    	    	fail("Invalid e-mail address should not have passed registration.");
    	    if(wr.getText().indexOf("Phone Number Format Invalid.")==-1)
    	    	fail("Invalid phone should not have passed registration.");

    }


    /**
     * Try to authenticate with a bad login/password
     * @throws Exception if an error occurs
     */
    private void tryBadAuth() throws Exception {
        WebResponse wRes = doAuth("bad", "bad");
        String txt = wRes.getText();

        if (txt.indexOf("Invalid username and/or password") == -1) {
            fail("The login/password bad/bad can't be a valid l/p.");
        }
    }

    /**
     * Try to authenticate with a right login/password
     * @throws Exception if an error occurs
     */
    private void tryWithGoodAuth() throws Exception {
        WebResponse wRes = doValidAuth();
        String txt = wRes.getText();

        if (txt.indexOf("Invalid username and/or password") != -1) {
            fail("The login/password jonas/jonas must be valid.");
        }
    }

    public void testAuthorization() throws Exception{
    	tryBadAuth();
    	tryWithGoodAuth();
    	logout();
    }

    private void logout() throws Exception{
    	WebResponse wr = wc.getResponse(getAbsoluteUrl(URL_OLSTORE_LOGOUT));

    	if(wr.getText().indexOf("Welcome to the RHAPS online store")==-1){
    		fail("Could not logout.");
    	}

    }


    public void testShoppingCartActivities() throws Exception{
    	doValidAuth();
    	if(!(addItemToShoppingCart() && purchaseItemInShoppingCart())){
    		fail("Activities related to session bean shopping cart failed.");
    	}
    	logout();
    }

    private boolean addItemToShoppingCart() throws Exception{
    	WebResponse wr = wc.getResponse(getAbsoluteUrl(URL_OLSTORE_ITEMS));
    	String str = OLSTORE_ITEM_DETAILS;
	WebLink wl = wr.getLinkWith(str);
    	if(wl==null){
		fail("Link for product details was not found.");
    		return false;
    	}else{
	 	WebResponse webR = wl.click();
		if(webR==null || webR.getText().indexOf(OLSTORE_ITEM_ADDTOCART)==-1){
    			fail("Link to shopping cart not found.");
    			return false;
		}else{
			wl = webR.getLinkWith(OLSTORE_ITEM_ADDTOCART);
			if(wl == null ||  wl.click().getText().indexOf("was successfully added")==-1){
				fail("Shopping Cart addition failed.");
    				return false;
			}else{
				return true;

			}

		}

	}
    }

    private boolean purchaseItemInShoppingCart() throws Exception{
    	String url= URL_OLSTORE_ITEM_PURCHASE;
    	WebResponse wr = wc.getResponse(getAbsoluteUrl(url));

    	WebForm[] webForms = wr.getForms();
        WebForm webForm = webForms[0];
	WebResponse submitPurchase = webForm.submit(webForm.getSubmitButton("", "order"));
        if(submitPurchase.getText().indexOf("The order was successfully placed!")==-1){
        	fail("Order couldn't be placed.");
        	return false;
        }
    	return true;

    }


    /**
     * Authenticate with a valid login/password
     * @return the response
     * @throws Exception if an error occurs
     */
    private WebResponse doValidAuth() throws Exception {
        return doAuth("jonas", "jonas");
    }

    /**
     * Authenticate with the specified login/password
     * @param login login to use
     * @param password password to use
     * @return the response after authentication
     * @throws Exception if an error occurs
     */
    private WebResponse doAuth(String login, String password) throws Exception {
        WebResponse wr = wc.getResponse(getAbsoluteUrl(URL_OLSTORE));
        WebForm[] webForms = wr.getForms();
        WebForm webForm = webForms[0];

        webForm.setParameter("username", login);
        webForm.setParameter("password", password);
        return webForm.submit();

    }


}
