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

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


public class F_JonasAdminRange extends JonasAdminTestCase {

    /**
     * URL of the Monitoring
     */
    private static final String URL_JONASADMIN_MONITORING = "EditMonitoring.do";

    /**
     * URL of the Memory
     */
    private static final String URL_JONASADMIN_MEMORY = "/jonasAdmin/EditMemory.do";

    /**
     * CONSTANT which is used to calculate the timer Graphic
     */
    private static final int CONSTANT = 2;

    /**
     * INITIAL RANGE VALUE
     */
    private static final String INITIAL_RANGE = "10";

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

    /**
     * Get a new TestSuite for this class
     * @return a new TestSuite for this class
     */
    public static TestSuite suite() {
        return new TestSuite(F_JonasAdminRange.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 monitoring range with a correct value
     * @throws Exception if error occurs
     *
     */
    public void testSuccessful() throws Exception {

        String range = "22";
        WebResponse wr;

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

        // Modify number of measures
        wr = modifyNbMeasures(range);

        // Verify range
        String text = wr.getText();
        int start = text.indexOf("function refresh()");
        int end = text.indexOf("}", start);
        // Get script
        String refreshScript = text.substring(start, end);

        // Get value
        start = refreshScript.indexOf("setTimeout(\"refresh()\", ") + "setTimeout(\"refresh()\", ".length();
        end = refreshScript.indexOf(");", start);
        String value = refreshScript.substring(start, end);

        // Verify refresh value in javascript function
        assertEquals("the range of the Memory image is wrong. ", "" + calculateTimerGraphic(range), value);

        // Verify error message
        assertFalse("there is an error message. ", wr.getElementsWithAttribute("class", "errors").length > 0);
    }

    /**
     * Test monitoring range with too small value
     * @throws Exception if error occurs
     *
     */
    public void testTooSmallValue() throws Exception {

        String range = "9";
        WebResponse wr;

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

        // Modify number of measures
        wr = modifyNbMeasures(range);

        // Verify error message
        assertTrue("there is not error message. ", wr.getElementsWithAttribute("class", "errors").length > 0);
    }

    /**
     * Test the memory servlet
     * @throws Exception if error occurs
     *
     */
    public void testMemoryServlet() throws Exception {
        WebResponse wr;
        WebLink link;

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

        // Go to Monitoring
        wr = wc.getFrameContents(FRAME_TREE);
        link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_MONITORING);
        link.click();
        wr = wc.getFrameContents(FRAME_CONTENT);

        // Go to Memory
        link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_MEMORY);
        link.click();
        wr = wc.getFrameContents(FRAME_CONTENT);

        // Refresh the image
        String servletUrl = prefixUrl + "/jonasAdmin/MemoryGraphServlet?1";
        WebResponse imgResponse = wc.getResponse(servletUrl);

        // Verify image
        assertEquals("'" + servletUrl + "' doesn't send a png image. ", "image/png", imgResponse.getHeaderField("CONTENT-TYPE"));

    }

    /**
     * Calculate the timer graphic
     * @param range range
     * @return timer graphic
     */
    public int calculateTimerGraphic(String range) {
        return (Integer.parseInt(range) + CONSTANT) * 1000;
    }

    /**
     * Modify range
     * @param range range
     * @return response
     * @throws Exception if error occurs
     */
    public WebResponse modifyNbMeasures(String range) throws Exception {

        // Go to Monitoring Memory
        WebResponse wr = wc.getResponse(getAbsoluteUrl(URL_JONASADMIN_MEMORY));

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

        webForm.setParameter("range", range);
        return wr = webForm.submit();
    }

    /**
     * Tear Down
     * cleanUp action
     */
    public void tearDown() throws Exception {
        super.tearDown();
        WebResponse wr = wc.getResponse(getAbsoluteUrl(URL_JONASADMIN_MEMORY));
        WebForm[] webForms = wr.getForms();
        WebForm webForm = webForms[0];

        webForm.setParameter("range", INITIAL_RANGE);
        wr = webForm.submit();
    }
}