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

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.HTMLElement;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * Class for testing discovery service
 * @author Paul Kemler
 *
 */
public class F_JonasAdminDiscovery extends JonasAdminTestCase {

    /**
     * URL of discovery service
     */
    private static final String URL_JONASADMIN_DISCOVERY = "EditServiceDiscovery.do";

    /**
     * number of tabs when you are in discovery
     */
    private static final int NUMBER_OF_TABS_FOR_DISCOVERY = 1;

    /**
     * Constructor with a specified name
     * @param s name
     */
    public F_JonasAdminDiscovery(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_JonasAdminDiscovery(testtorun));
        }
    }

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

    /**
     * Test discovery table
     * @throws Exception if error occurs
     *
     */
    public void testDiscovery() throws Exception {

        WebResponse wr;
        WebLink link;
        WebTable table;
        WebTable tabTable;
        int selectedTab;
        JonasAdminUtils utils = new JonasAdminUtils();

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

        // Test only if the discovery service is enabled
        if (jProp.isDiscovery()) {

            // Go to discovery service
            wr = wc.getFrameContents(FRAME_TREE);
            link = wr.getFirstMatchingLink( WebLink.MATCH_URL_STRING, URL_JONASADMIN_DISCOVERY);
            link.click();
            wr = wc.getFrameContents(FRAME_CONTENT);
            selectedTab = 1;

            // Verify multicast infos
            table = utils.getTable(wr, 0);
            // Multicast address
            String address = jProp.getPropertiesEnv().getProperty("jonas.service.discovery.multicast.address");
            assertEquals("It is not the expected multicast address. ", address, table.getTableCell(0, 2).getText());
            // Multicast port
            String port = jProp.getPropertiesEnv().getProperty("jonas.service.discovery.multicast.port");
            assertEquals("It is not the expected multicast port. ", port, table.getTableCell(1, 2).getText());

            // Verify action
            String master = table.getTableCell(2, 2).getText();
            table = utils.getTable(wr, 3);
            if (master.equals("true")) {
                // class="btnDisabled"
                HTMLElement[] btnDisabled = table.getTableCell(0, 0).getElementsWithAttribute("class", "btnDisabled");
                assertEquals("The class of the Start button is not 'btnDisabled'. ", 1, btnDisabled.length);

                // No link
                WebLink[] btnLink = table.getTableCell(0, 0).getLinks();
                assertEquals("There is a link on the Start button. ", 0, btnLink.length);
            } else {
                // No class="btnDisabled"
                HTMLElement[] btnDisabled = table.getTableCell(0, 0).getElementsWithAttribute("class", "btnDisabled");
                assertEquals("The class of the Start button is not 'btnDisabled'. ", 0, btnDisabled.length);

                // link=/DiscoveryServiceStartMaster.do
                WebLink[] btnLink = table.getTableCell(0, 0).getLinks();
                assertEquals("There is no link on the Start button. ", 1, btnLink.length);
                assertTrue("It is not the expected URL of the Start button. ", btnLink[0].getURLString().endsWith("/DiscoveryServiceStartMaster.do"));

                // Start Master
                btnLink[0].click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Verify is master
                table = utils.getTable(wr, 0);
                master = table.getTableCell(2, 2).getText();
                assertEquals("It is not master. ", "true", master);
                table = utils.getTable(wr, 3);
                // class="btnDisabled"
                btnDisabled = table.getTableCell(0, 0).getElementsWithAttribute("class", "btnDisabled");
                assertEquals("The class of the Start button is not 'btnDisabled'. ", 1, btnDisabled.length);

                // No link
                btnLink = table.getTableCell(0, 0).getLinks();
                assertEquals("There is a link on the Start button. ", 0, btnLink.length);
            }

            // Verify there is 1 tab
            tabTable = utils.getTabTable(wr);
            testTabs(tabTable, NUMBER_OF_TABS_FOR_DISCOVERY, selectedTab, "Problem in 'Discovery' tab.");
        }
    }

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

}
