/**
 * 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.domain;


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;

/**
 * Test adding a server to the domain.
 * @author Adriana Danes
 */
public class F_JonasAdminDomainAddServer extends JonasAdminTestCase {
    /**
     * message.domain.servers.none
     */
    private static final String MESSAGE_NO_SERVERS = "No other server in this domain!";
    /**
     * URL of "Create Jms Destination"
     */
    private static final String URL_DOMAIN_ADD_SERVER = "CreateJonasServer.do";
    /**
     *
     */
    private static final String APPLY_SERVERS_CONFIRM = "ApplyJonasServersConfirm.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 F_JonasAdminDomainAddServer(testtorun));
        }
    }

    /**
     * Get a new TestSuite for this class
     * @return a new TestSuite for this class
     */
    public static TestSuite suite() {
        return new TestSuite(F_JonasAdminDomainAddServer.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);
                }
            }
        }
    }


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

    /**
     * Test Add server action
     * @throws Exception if it fails
     *
     */
    public void testAddServer() throws Exception {
    	JonasAdminUtils utils = new JonasAdminUtils();
        // Disable errors of javascript
        HttpUnitOptions.setExceptionsThrownOnScriptError(false);

        // Get the frame "tree"
        WebResponse treeFrame = wc.getFrameContents(FRAME_TREE);

        // Create a request and go to the Domain page
        WebLink domainLink = treeFrame.getLinkWith("Domain");
        domainLink.click();

        // Get the response
        WebResponse wr = wc.getFrameContents(FRAME_CONTENT);

        // Click to the Add server
        WebLink link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_DOMAIN_ADD_SERVER);
        link.click();
        wr = wc.getFrameContents(FRAME_CONTENT);
        WebForm form = wr.getForms()[0];
        String createdServerName = "j1";
        form.setParameter("serverName", createdServerName);
        form.setParameter("serverURL", "url");

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

        // Go back to the Domain page
        domainLink.click();

        // Get the response
        wr = wc.getFrameContents(FRAME_CONTENT);

        // Go to Servers list
        WebTable table = utils.getTable(wr, 7);
        // Go to the 2nd column to find the created server name
        TableCell cell = table.getTableCell(0, 1);
        String actualServerName = cell.getText();

        assertEquals("The " + createdServerName + " was not found in the Servers list", createdServerName, actualServerName);

        // Remove the added server
        WebForm itemsServersForm = wr.getForms()[0];
        SubmitButton[] buttons = itemsServersForm.getSubmitButtons();
        //System.out.println("Nb submit buttons = " + buttons.length);
        itemsServersForm.setCheckbox("selectedItems", "jonas:j2eeType=J2EEServer,name=j1", true);
        /*
        String[] paramNames = itemsServersForm.getParameterNames();
        for (int i = 0; i < paramNames.length; i++) {
        	System.out.println("- " + paramNames[i]);
        }*/
        //itemsServersForm.setParameter("action", "remove");
        buttons[0].click();

        wr = wc.getFrameContents(FRAME_CONTENT);
        table = utils.getTable(wr, 0);
        /*
        cell = table.getTableCell(0, 0);
        text = cell.getText();
        System.out.println("---- " + text);*/
        // Confirm
        link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, APPLY_SERVERS_CONFIRM);
        link.click();

        // Go to domain page
        domainLink.click();
        wr = wc.getFrameContents(FRAME_CONTENT);

        // Go to Servers list
        table = utils.getTable(wr, 7);
        cell = table.getTableCell(0, 0);
        String text = cell.getText();
        boolean found;
        if (text.indexOf(MESSAGE_NO_SERVERS) >= 0) {
        	found = true;
        } else {
        	found = false;
        }
        assertTrue("Expecting " + MESSAGE_NO_SERVERS + ", found " + text, found);
    }
    /**
     * Tear Down cleanUp action
     * @throws Exception if an error occurs
     */
    public void tearDown() throws Exception {
        super.tearDown();
    }

}