/*
 * class: MonitorAnalysisTest
 *
 * Version $Id: MonitorAnalysisTest.txt,v 1.1 2004/01/30 20:25:04 mka Exp $
 *
 * Date: July 14 2003
 *
 * (c) 2003 IceCube Collaboration
 */

package icecube.testdaq.analysis.monitor.test;

import icecube.testdaq.analysis.monitor.MonitorAnalysis;
import icecube.testdaq.analysis.monitor.intervals.IntervalGroupList;
import icecube.testdaq.analysis.monitor.entry.ObjectFactory;
import icecube.testdaq.analysis.monitor.entry.MonitorRecordEntry;
import icecube.testdaq.analysis.monitor.entry.MonitorEntry;
import icecube.testdaq.analysis.monitor.entry.HardwareStateEventType;
import icecube.testdaq.analysis.monitor.limits.Limits;
import icecube.testdaq.analysis.monitor.limits.FixedLimitEntry;
import icecube.testdaq.analysis.monitor.limits.DerivedLimitEntry;
import icecube.testdaq.io.DataTypeException;

import junit.framework.*;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import java.util.Vector;
import java.math.BigInteger;

/**
 * This class defines the tests that any MonitorAnalysis object should pass.
 *
 * @version $Id: MonitorAnalysisTest.txt,v 1.1 2004/01/30 20:25:04 mka Exp $
 * @author phil
 */
public class MonitorAnalysisTest
        extends TestCase
{

    private MonitorAnalysis testObject;

    /**
     * Constructs and instance of this test.
     * @param name
     */
    public MonitorAnalysisTest(String name)
    {
        super(name);
    }

    /**
     * Tears down the fixture, for example, close a network connection.
     * This method is called after a test is executed.
     */
    protected void tearDown()
    {
        testObject = null;
    }

    /**
     * Explanation of test.
     */
    public void testSomething()
    {
    }

    // static member methods (alphabetic)

    /**
     * Create test suite for this class.
     */
    public static Test suite()
    {
        return new TestSuite(MonitorAnalysisTest.class);
    }

    // Description of this object.
    // public String toString() {}

    /**
     * Main routine which runs text test in standalone mode.
     */
    public static void main(String args[])
    {
        junit.textui.TestRunner.run(suite());

        Random random = new Random();
        MonitorAnalysis ma = null;
        try {
            ma = new MonitorAnalysis();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        Limits limits = createFakeLimits();
        Vector domMonitorRecords = getDOMs( random );

        try {

            BufferedOutputStream bos = null;
            JAXBContext jc = JAXBContext.newInstance( "icecube.testdaq.analysis.monitor.entry" );
            Marshaller m = jc.createMarshaller();
            m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );

            System.out.println( "******DOM INFORMATION BEFORE ANALYZING******" );

            for( int iDom = 0; iDom < domMonitorRecords.size(); iDom++ ){

                display( ( MonitorRecordEntry ) domMonitorRecords.get( iDom ) );
            }

            System.out.println( "******DOM INFORMATION AFTER ANALYZING******" );

            ArrayList igl = ma.analyze( limits, domMonitorRecords );

            bos = new BufferedOutputStream( new FileOutputStream( new File( "./Output.xml" ) ) );

            m.marshal( igl, bos );

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (JAXBException e) {
            e.printStackTrace();
        }catch (DataTypeException exc)
        {
            exc.printStackTrace();
        }

    }

    private static Limits createFakeLimits(){

        try {

            icecube.testdaq.analysis.monitor.limits.ObjectFactory of = new icecube.testdaq.analysis.monitor.limits.ObjectFactory();
            Limits limits = of.createLimits();
            List fixedLimits = limits.getFixedLimits();
            List derivedLimits = limits.getDerivedLimits();

            FixedLimitEntry  fle = of.createFixedLimitEntry();

            fle = of.createFixedLimitEntry();
            fle.setLowerBound( 30 );
            fle.setUpperBound( 40 );
            fle.setQuantity( "Temperature" );
            fle.setLimitIndex( 1 );

            fixedLimits.add( fle );

            DerivedLimitEntry dle = of.createDerivedLimitEntry();
            dle.setQuantity( "HighVoltage" );
            dle.setRestriction( "stable" );
            dle.setLimitIndex( 0 );

            derivedLimits.add( dle );

            return limits;

        } catch (javax.xml.bind.JAXBException e) {
            e.printStackTrace();  //To change body of catch statement use Options | File Templates.
        }

        return null;
    }

    private static Vector getDOMs( Random random ) {

        Vector temp = new Vector( );
        try {

            for( int j = 0; j < 5; j++ ){

                //  For now... create fake IntervalGroup objects
                ObjectFactory of = new ObjectFactory();
                MonitorRecordEntry mre = of.createMonitorRecordEntry();
                mre.setDomID( new String( new Integer( j ).toString() ) );
                List blankMonitorEntries = mre.getMonitorEntries( );

                for( int i = 0; i < 50; i++ ){

                    blankMonitorEntries.add( getNextEntry( random ) );
                }

                for( int i = 50; i < 100; i++ ){

                    blankMonitorEntries.add( getNextEntryLater( random ) );
                }

                for( int i = 0; i < 100; i++ ){

                    MonitorEntry currentMEntry = ( MonitorEntry ) blankMonitorEntries.get( i );
                    currentMEntry.setLocalTime( new BigInteger( new Integer( 100 - i ).toString() ) );
                }

                temp.add( mre );

            }

        } catch (JAXBException e) {

            e.printStackTrace();
        }

        return temp;
    }

        private static MonitorEntry getNextEntryLater( Random random ){

        try {

            ObjectFactory of = new ObjectFactory();
            MonitorEntry me = of.createMonitorEntry();
            me.getData().setPmtHv( (short) getRandomNumber(random) );
            me.getData().setTemperature( 35 + getRandomNumber( random ) );
            me.setLocalTime( new BigInteger(
                    new Integer( (int) Math.abs( getRandomNumber( random ) * 1000 ) ).toString() ) );

            return me;

        } catch (JAXBException e) {

            e.printStackTrace();
        }

        return null;
    }

    private static MonitorEntry getNextEntry( Random random ){

        try {

            ObjectFactory of = new ObjectFactory();
            MonitorEntry me = of.createMonitorEntry();

            me.getData().setPmtHv( (short) getRandomNumber(random) );
            me.getData().setTemperature( 35 + getRandomNumber( random ) );
            me.setLocalTime( new BigInteger(
                    new Integer( (int) Math.abs( getRandomNumber( random ) * 1000 ) ).toString() ) );

            return me;

        } catch (JAXBException e) {

            e.printStackTrace();
        }

        return null;
    }

    private static double getRandomNumber( Random random ){

        double x = 0, y = 0, sigma = 5;
        double functionValue = 0;
        do{
            x = ( 200 * random.nextDouble() ) - 100; // Random number between -100 and 100
            // The distributions value at x
            functionValue = ( 1 / ( Math.sqrt( 2 * Math.PI ) * sigma ) *
                    Math.exp( -( x*x ) / ( 2 * ( sigma * sigma ) ) ) );
            // A random number from zero to the height of the pulse
            y = ( 1 / ( Math.sqrt( 2 * Math.PI ) * sigma ) )* random.nextDouble();

        }while(y >= functionValue); // Loops until a value for x under the pulse is found

        return x;
    }

    private static void display( MonitorRecordEntry mre ){

        System.out.println( "Information on the current Interval Group for DOM: " +
                mre.getDomID() );
        List monitorEntries = mre.getMonitorEntries();

        for( int iEntry = 0; iEntry < monitorEntries.size(); iEntry++ ){

            MonitorEntry currentMonitorEntry = ( MonitorEntry ) monitorEntries.get( iEntry );

            System.out.println( "    Entry " + ( iEntry + 1 ) +
                    ") Time: " +  currentMonitorEntry.getLocalTime().toString() +
                    "   HighVoltage: " + currentMonitorEntry.getData().
                    getPmtHv() + "   Temperature: " + currentMonitorEntry.
                    getData().getTemperature() );

        }
    }

}
