/*
 * ProcessSuite
 */
package com.company.test;

import java.io.File;

import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestSuite;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

/**
 * Provides a test suite that contains all tests of the package
 * {@link com.company.test}.
 *
 * @author Ralf Kintrup
 */
public class ProcessSuite {
    private static final Log log = LogFactory.getLog(ProcessSuite.class);
    private static Selenium selenium = null;

    public static Test suite() {
        TestSuite suite = new TestSuite();

        // Add test cases to the suite below.
        log.debug("Setting up test suite.");
        suite.addTestSuite(WebProcessTest.class);

        TestSetup wrapper = new TestSetup(suite) {
            protected void setUp() {
                oneTimeSetUp();
            }

            protected void tearDown() {
                oneTimeTearDown();
            }
        };

        return wrapper;
    }

    public static Selenium getSelenium() {
        Selenium res = null;
        if (selenium != null) {
            res = selenium;
        } else {
            throw new IllegalStateException("No Selenium instance available. Use the test suite in class " + ProcessSuite.class.toString() + " to start the tests.");
        }
        return res;
    }

    public static void oneTimeSetUp() {
        String sWebRoot = "C:\\Programme\\tomcat5.5\\webapps";
        File fWebAppRoot = null;
        if (selenium == null) {
            fWebAppRoot = new File(sWebRoot);
            if (fWebAppRoot == null) {
                throw new RuntimeException("Failed to find web root folder: " + sWebRoot);
            }
            selenium = new DefaultSelenium(fWebAppRoot);
            if (selenium == null) {
                throw new RuntimeException("Could not create Selenium instance.");
            }
            selenium.start();
            log.debug("Started Selenium instance.");
        } else {
            log.error("Called more than once. Check correct usage.");
        }
    }

    public static void oneTimeTearDown() {
        if (selenium != null) {
            selenium.stop();
            selenium = null;
            log.debug("Stopped Selenium instance and set reference to 'null'.");
        } else {
            log.error("No instance of Selenium found when trying to cleanup. Check correct usage.");
        }
    }
}

