/*
 * 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 junit.framework.TestSuite;

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

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;

/**
 * Define a class to test the JOnAS Admin console
 * Test authentication and deploy/undeploy ears
 * @author Florent Benoit
 */
public class F_JonasAdminDeploy extends JonasAdminTestCase {

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

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

    /**
     * Get a new TestSuite for this class
     * @return a new TestSuite for this class
     */
    public static TestSuite suite() {
        return new TestSuite(F_JonasAdminDeploy.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");
        } else {
            // if there was an error, the connection must be restablished
            try {
                wc.getFrameContents(FRAME_TREE);
            } catch (Exception e) {
                wc.getResponse(urlLogOut);
            }
        }
    }


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

    /**
     * Try to authenticate with a bad login/password
     * @throws Exception if an error occurs
     */
    public void testTryBadAuth() throws Exception {
        // login to jonas admin
        WebResponse wRes = JonasAdminAuth.doAuth(wc, url, "bad", "bad");
        String txt = wRes.getText();

        if (txt.indexOf("Invalid username 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
     */
    public void testTryWithGoodAuth() throws Exception {
        WebResponse wRes = JonasAdminAuth.doValidAuth(wc, url);
        String txt = wRes.getText();

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

    /**
     * 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
        WebTable bigTable = wr.getTables()[0];
        WebTable firstTable = bigTable.getTableCell(1, 0).getTables()[0];
        WebTable cellTable = firstTable.getTableCell(0, 0).getTables()[0];
        WebTable subTable = cellTable.getTableCell(0, 0).getTables()[0];

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

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


    /**
     * Deploy the ear with the testcase method and then, try to undeploy the ear with jonaAdmin
     * If it was undeployed, deploy it again with jonasAdmin
     * @param name of the ear (without extension) to test
     * @throws Exception if an error occurs
     */
    private void unDeployAndDeployEar(String name) throws Exception {
        String fileName = name + ".ear";
        String url = URL_JONASADMIN_DEPLOYEAR;

        //First load Ear
        useEar(name);

        WebResponse wr = wc.getResponse(getAbsoluteUrl(url));

        String txt = getDeployTable(wr, true);

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

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

        String params = webForm.getParameterValue("undeploy");
        WebForm.Scriptable script = webForm.getScriptableObject();

        // Disable errors of javascript
        HttpUnitOptions.setExceptionsThrownOnScriptError(false);

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

        script.setParameterValue("undeploy", params);

        WebResponse submitUndeploy = webForm.submit();

        // ear is in the table
        webForms = submitUndeploy.getForms();
        webForm = webForms[0];

        WebResponse endResp = webForm.submit();


        wr = wc.getResponse(getAbsoluteUrl(url));
        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);

        submitUndeploy = webForm.submit();

        // ear is in the table
        webForms = submitUndeploy.getForms();
        webForm = webForms[0];

        endResp = webForm.submit();

        wr = wc.getResponse(getAbsoluteUrl(url));
        txt = getDeployTable(wr, true);

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

    /**
     * Deploy the ear with the testcase method and then, try to undeploy the ear with jonaAdmin
     * If it was undeployed, deploy it again with jonasAdmin
     * Test with ears alarm cmp2 and earsample
     * @throws Exception if an error occurs
     */
    public void testTryDeployUndeployEars() throws Exception {
        // login to jonas admin
        if (wc.getCurrentPage().getURL() == null) {
            // 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);
                }
            }
        }

        unDeployAndDeployEar("alarm");
        unDeployAndDeployEar("cmp2");
        if (jProp.isResource()) {
            unDeployAndDeployEar("earsample");
        }
    }

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