/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2005 Bull S.A.
 * Contact: jonas-team@objectweb.org
 *
 * 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 1any 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
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.jonasadmin.test.deploy;

import java.io.File;

import junit.framework.TestSuite;

import org.objectweb.jonas.jonasadmin.test.util.JonasAdminAuth;
import org.objectweb.jonas.jonasadmin.test.util.JonasAdminTestCase;
import org.objectweb.jonas.jonasadmin.test.util.JonasAdminUtils;

import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.SubmitButton;
import com.meterware.httpunit.TableCell;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * Class for testing deploy/undeploy wars
 * @author Paul Kemler
 */
public class F_JonasAdminDeployWar extends JonasAdminTestCase {

    /**
     * URL of the deployment of WARs
     */
    protected static final String URL_JONASADMIN_DEPLOYWAR = "EditDeploy.do?type=war";

    /**
     * URL of the deployment
     */
    protected static final String URL_JONASADMIN_DEPLOY = "EditDeploy.do";

    /**
     * URL of UPLOAD
     */
    protected static final String URL_JONASADMIN_UPLOAD = "EditUpload.do";

    /**
     * URL of REMOVE
     */
    protected static final String URL_JONASADMIN_REMOVE = "EditRemove.do";

    /**
     * number of tabs when you are in the deployment tabs
     */
    private static final int NUMBER_OF_TABS_FOR_DEPLOYMENT = 3;

    /**
     * number of tabs when you are in the CONFIRM tabs
     */
    private static final int NUMBER_OF_TABS_FOR_CONFIRM = 4;

    /**
     * Constructor with a specified name
     * @param s name
     */
    public F_JonasAdminDeployWar(String s) {
        super(s, URL_JONASADMIN);
    }

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

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

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

        if (wc.getCurrentPage().getURL() == null) {
            useWar("jonasAdmin");
            // login to jonas admin
            try {
                JonasAdminAuth.doValidAuth(wc, url);
            } catch (Exception e) {
                fail("authentification failed :  " + e);
            }
        } else {
            // if there was an error, the connection must be restablished
            try {
                wc.getFrameContents(FRAME_TREE);
            } catch (Exception e) {
                wc.getResponse(urlLogOut);
                // login to jonas admin
                try {
                    JonasAdminAuth.doValidAuth(wc, url);
                } catch (Exception auth) {
                    fail("authentification failed :  " + auth);
                }
            }
        }
    }

    /**
     * Return the text of the deployed table or the deployable table
     * @param wr the WebResponse to use
     * @param deployed if true return the text deployed table, if false text of
     *        deployable
     * @return the text of the deployed table or the deployable table
     * @throws Exception if an error occurs
     */
    private String getDeployTable(WebResponse wr, boolean deployed) throws Exception {

        // Extract right table
        JonasAdminUtils utils = new JonasAdminUtils();
        WebTable table = utils.getTable(wr, 0);

        TableCell deployableCell = table.getTableCell(1, 0);
        TableCell deployedCell = table.getTableCell(1, 2);

        if (deployed) {
            return deployedCell.getText();
        } else {
            return deployableCell.getText();
        }
    }

    /**
     * Deploy the war with the testcase method and then, try to undeploy the war
     * with jonaAdmin If it was undeployed, deploy it again with jonasAdmin Test
     * with war autoload/ctxroot.war
     * @throws Exception if an error occurs
     */
    public void testTryDeployUndeployWars() throws Exception {

        WebResponse wr;
        WebLink link;
        WebTable table;
        WebTable tabTable;
        int selectedTab;
        /*
         * To get some utils for WebTable
         */
        JonasAdminUtils utils = new JonasAdminUtils();

        // Disable errors of javascript
        HttpUnitOptions.setExceptionsThrownOnScriptError(false);
        // Disable exception thrown on error status
        HttpUnitOptions.setExceptionsThrownOnErrorStatus(false);

        // First load War
        String name = "autoload" + File.separator + "ctxroot";
        String fileName = name + ".war";
        useWar(name);

        // Go to Deployment/WebModules
        wr = wc.getFrameContents(FRAME_TREE);
        link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_DEPLOYWAR);
        link.click();
        wr = wc.getFrameContents(FRAME_CONTENT);
        selectedTab = 1;

        // Verify tabs
        tabTable = utils.getTabTable(wr);
        testTabs(tabTable, NUMBER_OF_TABS_FOR_DEPLOYMENT, selectedTab, "Problem in 'Deployment' tab.");
        // - links
        assertTrue("The link " + URL_JONASADMIN_UPLOAD + " is not found in the second tab. ", tabTable.getTableCell(0,
                2).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_UPLOAD));
        assertTrue("The link " + URL_JONASADMIN_REMOVE + " is not found in the third tab. ", tabTable
                .getTableCell(0, 4).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_REMOVE));

        String txt = getDeployTable(wr, true);

        if (txt.indexOf(fileName) == -1) {
            fail("The file" + fileName + " was not found as deployed.");
        }

        // Undeploy
        WebForm[] webForms = wr.getForms();
        WebForm webForm = webForms[0];

        String params = webForm.getParameterValue("undeploy");
        WebForm.Scriptable script = webForm.getScriptableObject();
        if (params.length() == 0) {
            params += fileName;
        } else {
            params += "," + fileName;
        }
        script.setParameterValue("undeploy", params);

        SubmitButton button = webForm.getSubmitButtons()[0];
        button.click();

        // Confirm
        WebResponse submitUndeploy = wc.getFrameContents(FRAME_CONTENT);
        selectedTab = 2;

        // Verify tabs
        tabTable = utils.getTabTable(submitUndeploy);
        testTabs(tabTable, NUMBER_OF_TABS_FOR_CONFIRM, selectedTab, "Problem in 'Confirm' tab.");
        // - links
        assertTrue("The link " + URL_JONASADMIN_DEPLOY + " is not found in the first tab. ", tabTable.getTableCell(0,
                0).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_DEPLOY));
        assertTrue("The link " + URL_JONASADMIN_UPLOAD + " is not found in the third tab. ", tabTable.getTableCell(0,
                4).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_UPLOAD));
        assertTrue("The link " + URL_JONASADMIN_REMOVE + " is not found in the fourth tab. ", tabTable
                .getTableCell(0, 6).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_REMOVE));

        webForms = submitUndeploy.getForms();
        webForm = webForms[0];

        button = webForm.getSubmitButtons()[0];
        button.click();
        wr = wc.getFrameContents(FRAME_CONTENT);

        // Verify tabs
        tabTable = utils.getTabTable(wr);
        testTabs(tabTable, NUMBER_OF_TABS_FOR_CONFIRM, selectedTab, "Problem in 'Result' tab.");
        // - links
        assertTrue("The link " + URL_JONASADMIN_DEPLOY + " is not found in the first tab. ", tabTable.getTableCell(0,
                0).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_DEPLOY));
        assertTrue("The link " + URL_JONASADMIN_UPLOAD + " is not found in the third tab. ", tabTable.getTableCell(0,
                4).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_UPLOAD));
        assertTrue("The link " + URL_JONASADMIN_REMOVE + " is not found in the fourth tab. ", tabTable
                .getTableCell(0, 6).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_REMOVE));

        // Go back to Deployment
        link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_DEPLOY);
        link.click();
        wr = wc.getFrameContents(FRAME_CONTENT);
        selectedTab = 1;

        // Verify tabs
        tabTable = utils.getTabTable(wr);
        testTabs(tabTable, NUMBER_OF_TABS_FOR_DEPLOYMENT, selectedTab, "Problem in 'Deployment' tab.");
        // - links
        assertTrue("The link " + URL_JONASADMIN_UPLOAD + " is not found in the second tab. ", tabTable.getTableCell(0,
                2).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_UPLOAD));
        assertTrue("The link " + URL_JONASADMIN_REMOVE + " is not found in the third tab. ", tabTable
                .getTableCell(0, 4).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_REMOVE));


        txt = getDeployTable(wr, true);

        if (txt.indexOf(fileName) != -1) {
            fail("The jonasAdmin webApp has not removed. " + fileName);
        }

        // now deploy
        webForms = wr.getForms();
        webForm = webForms[0];

        params = webForm.getParameterValue("deploy");
        script = webForm.getScriptableObject();

        if (params.length() == 0) {
            params += fileName;
        } else {
            params += "," + fileName;
        }

        script.setParameterValue("deploy", params);
        button = webForm.getSubmitButtons()[0];
        button.click();

        // Confirm
        submitUndeploy = wc.getFrameContents(FRAME_CONTENT);
        // war is in the table
        webForms = submitUndeploy.getForms();
        webForm = webForms[0];

        button = webForm.getSubmitButtons()[0];
        button.click();

        // Go back to Deployment
        wr = wc.getFrameContents(FRAME_CONTENT);
        link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_DEPLOY);
        link.click();
        wr = wc.getFrameContents(FRAME_CONTENT);

        txt = getDeployTable(wr, true);

        if (txt.indexOf(fileName) == -1) {
            fail("The file " + fileName + " was not found as deployed.");
        }
    }

    /**
     * Tear Down cleanUp action
     * @throws Exception if an error occurs
     */
    public void tearDown() throws Exception {
        super.tearDown();
    }

}
