/**
 * 
 * 
 * 
 * 	copyright(c)1998 Timothy M. Radonich
 * 	 
 * 
 * 	 
 * 	@see	http://www.whatrain.com/javatest/metric/WhatRainConverter.class
 * 	@version	1.00
 * 	@author	Timothy M. Radonich timmy@whatrain.com
 *	
 *	@since jdk1.02
 */
/*
* Copyright (c) 1998 Timothy M.Radonich. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for NON-COMMERCIAL or COMMERCIAL purposes and without fee is
* hereby granted.
* 
* WHATRAIN WWW SERVICES NOR TIMOTHY M. RADONICH MAKE NO REPRESENTATIONS OR 
* WARRANTIES ABOUT THE SUITABILITY OF THE
* SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
* NON-INFRINGEMENT. WHATRAIN WWW SERVICES NOR TIMOTHY M. RADONICH  SHALL 
* NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
* LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR
* ITS DERIVATIVES.
* 
* THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
* CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE PERFORMANCE,
* SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT NAVIGATION OR
* COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE SUPPORT MACHINES, OR
* WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE SOFTWARE COULD LEAD DIRECTLY TO
* DEATH, PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH
* RISK ACTIVITIES"). WHATRAIN WWW SERVICES AND TIMOTHY M. RADONICH  
* SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED
* WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES.
*/

import java.awt.*;
import java.util.*;
import java.io.*;
import java.net.*;

public class WhatRainConverter extends java.applet.Applet
{

	Choice conversionSelect;	//choice of conversion type
	TextField inputNumber;		// enter value to be converted
	Label output;			//display for output of converted value
	Label label2;			//for "WhatRain" title
	Label typeLable;		//for general type of conversion display set in parameter named "type"
	Label label3;			// display "Converter"
	Label conversionLabel;		//display "equals"	
	Label label1;			// display instuctions

	int noc;			// number of conversions read from parameter
	double multipliers[];		//array to hold the conversion mulipiers indexed to Choice conversionSelect

	public void init()
	{
		setLayout( null );	//no layout manager 
		setForeground( new Color( 0, 0, 0 ));		//black
		setBackground( new Color( 255, 255, 255 ));	//white
		addNotify();					// call before resize or font metrics
		// set applet size  
		resize( (insets().left + insets().right + 475), (insets().top + insets().bottom + 172) );
		// add choice drop down list for conversion choices
		conversionSelect = new Choice();
		// get number of converstions from parameter
		String numberofconversions = getParameter("numberOfConversions");
		try  // parseInt throws NumberFormatException
		{
			noc = Integer.parseInt(numberofconversions);
		}
		catch(NumberFormatException e)
		{
			// do nothing html not properly set -- crash
		}

		multipliers = new double[noc];	//set array to number of conversions
		for ( int i = 0 ; i < noc ; i++ )	
		{		//go through the list of parameters index

			Integer n = new Integer(i);	//get index #

			String s = n.toString();	//convert to string
			// concate string for parameter call
			String param = getParameter("conversion" + s);
			// pass parameter to unitConverstionInfo to be parsed
			unitConversionInfo uci = new unitConversionInfo(param);
			// set multiplier index to conversion ratio
			multipliers[i]= uci.getMultiplier();
			//add Choice conversionSelect for index conversion types
			conversionSelect.addItem( uci.getFrom() + " to " + uci.getTo());

		}


		conversionSelect.setFont( new Font( "Dialog", Font.PLAIN, 20 ));	//set font
		conversionSelect.setBackground( new Color( 255, 255, 255 ));		//white
		add( conversionSelect );
		conversionSelect.reshape( (insets().left + 30), (insets().top + 77), 415, 28 );

		// input text feild 	 reshape() is Deprecated

		inputNumber = new TextField( "0" );
		inputNumber.setEditable( true );
		inputNumber.setFont( new Font( "Dialog", Font.PLAIN, 20 ));
		inputNumber.setBackground( new Color( 255, 255, 255 ));
		add( inputNumber );
		inputNumber.reshape( (insets().left + 30), (insets().top + 120), 118, 28 );

		// output lable 	 reshape() is Deprecated
		output = new Label( "", Label.LEFT );
		output.setFont( new Font( "Dialog", Font.PLAIN, 20 ));
		add( output );
		output.reshape( (insets().left + 272), (insets().top + 121), 173, 28 );

		//WhatRain lable 	 reshape() is Deprecated
		label2 = new Label( "WhatRain", Label.LEFT );
		label2.setFont( new Font( "Dialog", Font.PLAIN, 40 ));
		label2.setForeground( new Color( 0, 0, 160 ));
		add( label2 );
		label2.reshape( (insets().left + 29), (insets().top + 16), 180, 42 );

		String t = getParameter("type");// get "type" parameter

		// type lable 	 reshape() is Deprecated
		typeLable = new Label( t, Label.LEFT );
		typeLable.setFont( new Font( "Dialog", Font.PLAIN, 22 ));
		add( typeLable );
		typeLable.reshape( (insets().left + 213), (insets().top + 14), 206, 24 );

		//"Converter" lable 	 reshape() is Deprecated
		label3 = new Label( "Converter", Label.LEFT );
		label3.setFont( new Font( "Dialog", Font.PLAIN, 25 ));
		add( label3 );
		label3.reshape( (insets().left + 212), (insets().top + 41), 115, 20 );

		//"equals" lable 	 reshape() is Deprecated
		conversionLabel = new Label( "equals", Label.CENTER );
		conversionLabel.setFont( new Font( "Dialog", Font.PLAIN, 20 ));
		add( conversionLabel );
		conversionLabel.reshape( (insets().left + 179), (insets().top + 121), 80, 28 );

		// instruction lable 	 reshape() is Deprecated
		label1 = new Label( "Select the conversion type. Input the value and press enter.", Label.LEFT );
		label1.setFont( new Font( "Dialog", Font.PLAIN, 8 ));
		add( label1 );
		label1.reshape( (insets().left + 33), (insets().top + 154), 423, 18 );

		inputNumber.requestFocus();			// set focus on input
		inputNumber.selectAll();			// prepare for input




	}



	protected void InputNumberActionEvent( Event event )	
	{	//enter pressed while inputNumber has focus

			String input = inputNumber.getText();		//get input text
			try
			{	//Double(String)  throws NumberFormatException
			Double n = new Double(input);			//change to Double
			double ip = n.doubleValue();			//change to double
			int i = conversionSelect.getSelectedIndex();	//get the selected convertion	
			double op = ip * multipliers[i];		//input times convertion value
			String o = DoubleFormat.toString(op , -4);	//remove trailing 0s and convert to string
			output.setText(o); 				//results to output lable
			}
			catch(NumberFormatException e)
			{  // no a number try again
				inputNumber.requestFocus();			// set focus on input
				inputNumber.selectAll();			// prepare for input
				output.setText(""); 				//clear output lable
			}

			inputNumber.requestFocus();			// set focus on input
			inputNumber.selectAll();			// prepare for next input

	}
	protected void ConversionSelectSelected( Event event )
	{
		inputNumber.requestFocus();			// set focus on input
		inputNumber.selectAll();			// prepare for input
		output.setText(""); 				//clear output lable

	}


	public boolean handleEvent( Event event )
	{
		if ((event.target == conversionSelect) && (event.id == Event.ACTION_EVENT))
		{  // selection made
			ConversionSelectSelected( event );
			return true;	// event handled
		}


		else if ((event.target == inputNumber) && (event.id == Event.ACTION_EVENT))
		{  // enter pressed while input has focus
			InputNumberActionEvent( event );
			return true;	// event handled
			
		}
		else // not our events use default handleEvent(event)
			return super.handleEvent(event); 

	}

	public void start()
	{

	}

	public void stop()
	{

	}

}


/**
 * 
 * 
 * 
 * 	copyright(c)1998 Timothy M. Radonich
 * 	 
 * 
 * 	 
 * 	@see	http://www.whatrain.com/javatest/metric/WhatRainConverter.class
 * 	@version	1.00
 * 	@author	Timothy M. Radonich timmy@whatrain.com
 *	
 *	@since jdk1.02
 */
class unitConversionInfo
{
	String from;	//hold the from conversion type
	String to;	//hold the to conversion type
	double multiplier; // hold the conversion multiplier
	
	unitConversionInfo(String param)
	{	//param value = "unitFrom,unitTo,multiplier"
		//"|" delineated
			StringTokenizer st = new StringTokenizer(param , "|");
			from = st.nextToken();
			to = st.nextToken();
			String m = st.nextToken();
			try
			{	//Double(String)  throws NumberFormatException
				Double mx = new Double(m);  //param string to Double
				multiplier = mx.doubleValue();// Double to double
			}
			catch(NumberFormatException e)
			{
				// do nothing html not properly set -- crash

			}
	}
	double getMultiplier()
	{
		return multiplier;
	}

	String getFrom()
	{
		return from;
	}

	String getTo()
	{
		return to;
	}

}

/**
 * 
 * 
 * 
 * 	copyright(c)1997 Jamsa Press
 * 	 
 * 
 * 	 
 * 	@see	http://www.whatrain.com/javatest/metric/DoubleFormat.class
 * 	@version	1
 * 	@author	1001 Java Programmer's Tips
 *	
 *	@since jdk1.0
 */
class DoubleFormat {
   public static String toString(double inValue, int precision) {
      return toString(inValue, precision, false);
    }

   public static String toString (double inValue, int precision,
      boolean use_comma)
    {
      boolean trailing_zero;
      double absval= Math.abs(inValue); // get positive portion

      if (precision < 0)
        {
          precision = -precision;
          trailing_zero = false;
        }
      else
         trailing_zero = true;

      String signStr = "";

      if (inValue < 0)
         signStr= "-";

      long intDigit = (long) Math.floor(absval); // get integer part

      String intDigitStr = String.valueOf(intDigit);

      if (use_comma)
        {
          int intDigitStrLen= intDigitStr.length();
          int dig_index= (intDigitStrLen - 1) % 3;

          dig_index++;

          String intCommaDigitStr = intDigitStr.substring(0,
            dig_index);

         while (dig_index < intDigitStrLen)
           {
             intCommaDigitStr += "," +
               intDigitStr.substring(dig_index, dig_index+3);

             dig_index+= 3;
           }
         intDigitStr= intCommaDigitStr;
       }

     String precDigitStr= "";

     long precDigit= Math.round((absval - intDigit) * 
           Math.pow(10.0, precision));

     precDigitStr= String.valueOf(precDigit);

     // pad zeros between decimal and precision digits
     String zeroFilling= "";

     for (int i= 0; i < precision-precDigitStr.length(); i++)
         zeroFilling += "0";

      precDigitStr= zeroFilling + precDigitStr;

      if (!trailing_zero)
        {
           int lastZero;

           for (lastZero = precDigitStr.length() - 1; 
                lastZero >= 0; lastZero--)
             if (precDigitStr.charAt(lastZero)!= '0')
                break;

           precDigitStr= precDigitStr.substring(0, lastZero + 1);
        }

      if (precDigitStr.equals(""))
         return signStr + intDigitStr;
      else
         return signStr + intDigitStr + "." + precDigitStr;
    }
  }


