package com.maplesoft.maplenet.demo;

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.URL;
import javax.swing.*;

import com.maplesoft.client.*;

public class MathTest extends Applet {
   boolean isStandalone = false;

   String host;
   int port;
   String user;
   String password;

   JLabel promptString = new JLabel();
   JTextField inputString = new JTextField();
   JButton jButton1 = new JButton();
   JButton jButton2 = new JButton();
   JButton jButton3 = new JButton();
   JLabel statusString = new JLabel("Status:  ");
	 GridBagLayout      gbl = new GridBagLayout();
	 GridBagConstraints gbc = new GridBagConstraints();

   // **************************************************
   // Create the panel that will display the Equation
   // **************************************************
   mathmlEquation equation = new mathmlEquation();

   //Get a parameter value
   public String getParameter(String key, String def) {
      return isStandalone ? System.getProperty(key, def) :
         (getParameter(key) != null ? getParameter(key) : def);
   }

   //Construct the applet
   public MathTest() {
   }

   //Initialize the applet
   public void init() {
      try {
         URL url = getDocumentBase();
         String sDocHost = url.getHost();

         host = this.getParameter( "host", sDocHost );
         //host = "localhost";
      }
      catch(Exception e) {
         e.printStackTrace();
      }
      try {
         port = Integer.parseInt(this.getParameter("port", "14444"));
      }
      catch(Exception e) {
         e.printStackTrace();
      }
      try { port = Integer.parseInt(this.getParameter("port", "14444")); } catch (Exception e) { e.printStackTrace(); }
      try {
         user = this.getParameter("usuário", "cliente");
      }
      catch(Exception e) {
         e.printStackTrace();
      }
      try {
         password = this.getParameter("senha", "demopass");
      }
      catch(Exception e) {
         e.printStackTrace();
      }
      try {
         jbInit();
         myInit();
         sizecheck();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }

   private void sizecheck() {

      int w = getWidth();
      int h = getHeight();
      int x1;
      int y1;
      int w1;
      int h1;
      x1= inputString.getX();
      y1= inputString.getY();
      h1 = inputString.getHeight();
      w1 = (w-2*x1);
      if(w1 < 20) w1 = 20;
      inputString.setSize( w1, h1 );

      h1 = equation.getHeight();
      equation.setSize(w1, h1);

      x1= jButton1.getX();
      w1 = (w-2*x1);
      if(w1 < 20) w1 = 20;
      h1 = jButton1.getHeight();
      jButton1.setSize( w1, h1 );
   }

   private void myInit() {

      // ***************************************************************
      // Allow the equation to use text size controls (right mouse click)
      // Set the position of the equation on the panel on the Applet
      // Allow the equatiion to be copied to clipboard
      // ***************************************************************
      equation.setControls( true );
      equation.setLocation( 25, 100 );
      equation.allow_cut = true;

   }

   //Component initialization
   private void jbInit() throws Exception {

		 this.setLayout(gbl);
		 gbc.gridx = 0;
		 gbc.gridy = 0;
		 gbc.weightx = 1;
		 gbc.weighty = 0;
		 gbc.gridwidth = 2;
		 gbc.gridheight = 1;
		 gbc.anchor = GridBagConstraints.NORTHWEST;
		 gbc.insets = new Insets(10, 10, 10, 10);
		 promptString.setText("Considere a seguinte transfer function para um processo de Laplace domain");
		 this.add( promptString, gbc);

		 gbc.gridy = 1;
		 gbc.weightx = 0;
		 gbc.weighty = 1;
		 gbc.fill = GridBagConstraints.BOTH;
		 equation.setBackground(SystemColor.info);
     this.add( equation, gbc );

     gbc.gridy = 2;
     gbc.gridwidth = 1;
     gbc.weighty = 0;
     gbc.fill = GridBagConstraints.NONE;
     this.add( new JLabel( "1.  What is the order of the transfer function?"), gbc );

     gbc.gridx = 1;
     gbc.fill = GridBagConstraints.HORIZONTAL;
     this.add( inputString, gbc );

     gbc.gridy = 3;
     gbc.gridx = 0;
     gbc.anchor = GridBagConstraints.CENTER;
     gbc.fill = GridBagConstraints.NONE;
     jButton1.setText("Submit");
     jButton1.addActionListener(new MathTest_jButton1_actionAdapter(this));
     this.add( jButton1, gbc );

     gbc.gridx = 1;
     jButton2.setText("Próximo");
		 jButton2.addActionListener(new MathTest_jButton2_actionAdapter(this));
     this.add( jButton2, gbc );

		 gbc.gridy = 4;
		 gbc.gridx = 0;
		 gbc.gridwidth = 2;
		 gbc.weighty = 1;
		 gbc.anchor = GridBagConstraints.NORTHWEST;
		 gbc.fill = GridBagConstraints.VERTICAL;
		 this.add( statusString, gbc );

		 setEquation("Gp(s)=K*exp(-3*s)/((3*s+1)*(7*s+1))");
			this.invalidate();
			this.validate();
   }

   //Get Applet information
   public String getAppletInfo() {
      return "Applet Informação";
   }

   //Get parameter info
   public String[][] getParameterInfo() {
      String[][] pinfo =
         {
         {"host", "String", ""},
         {"port", "int", ""},
         {"usuário", "String", ""},
         {"senha", "String", ""},
         };
      return pinfo;
   }

   private void setEquation(String eq) {
		   String sOutput;

		   System.out.println("Tente   :"+host+":"+port+"  usuário="+user);
		   System.out.println("Entrada :"+eq);
			 MapleToMathML convertor = new MapleToMathML( host, port, user, password );
			 try {
					convertor.execute( eq, 2 );
					sOutput = convertor.getResult();
					System.out.println("Saída :"+sOutput);

					equation.setEquation( sOutput );
			 } catch( Exception ex ) {
					System.out.println( "Erro de conversão" + ex.toString() );
					equation.setEquation( "<math><mi>?</mi></math>" );
			 }
       //repaint();
	 }

   void Submit_actionPerformed(ActionEvent e) {
      String sInput;
      String sOutput;
      sInput = "simplify(" + inputString.getText() + " - 2)";
      System.out.println("Tente   :"+host+":"+port+"  usuário="+user);
      System.out.println("Entrada :"+sInput);
      MapleStatement cmd = new MapleStatement( host, port, user, password );
      String answer;

      // Must catch exceptions that might be generated
      try {
         // Take raw text from Command Line and forward to Server using 'execute()'
         // Store the result in answer
         answer = cmd.execute( sInput );
      }catch( Exception ex ) {
         // Use the exception as the answer
         answer = ex.toString();
      }
			System.out.println( "Resultado: |" + answer + "|");
			if ( answer.equals( "0" ) )
				 statusString.setText( "Status:  Correto" );
		  else
				 statusString.setText( "Status:  Incorreto" );

      invalidate();
			validate();
			//layout();

      //repaint();
   }

   void Submit_Question2(ActionEvent e) {
      String sInput;
      String sOutput;
      sInput = "simplify(" + inputString.getText() + " - (1-(3/2)*s)/(1+(3/2)*s))";
      System.out.println("Tente   :"+host+":"+port+"  usuário="+user);
      System.out.println("Entrada :"+sInput);
      MapleStatement cmd = new MapleStatement( host, port, user, password );
      String answer;

      // Must catch exceptions that might be generated
      try {
         // Take raw text from Command Line and forward to Server using 'execute()'
         // Store the result in answer
         answer = cmd.execute( sInput );
      }catch( Exception ex ) {
         // Use the exception as the answer
         answer = ex.toString();
      }
			System.out.println( "Resultado: |" + answer + "|");
			if ( answer.equals( "0" ) || answer.equals( "0." ) )
				 statusString.setText( "Status:  Correto" );
		  else
				 statusString.setText( "Status:  Incorreto" );

      invalidate();
			validate();
			//layout();

      //repaint();
   }

   void NextQuestion(ActionEvent e) {

		 this.removeAll();

		 gbc.gridx = 0;
		 gbc.gridy = 0;
		 gbc.weightx = 1;
		 gbc.weighty = 0;
		 gbc.gridwidth = 2;
		 gbc.gridheight = 1;
		 gbc.anchor = GridBagConstraints.NORTHWEST;
		 gbc.insets = new Insets(10, 10, 10, 10);
		 promptString.setText("2. What is the first-order pade approximation of");
		 this.add( promptString, gbc);

		 gbc.gridy = 1;
		 gbc.fill = GridBagConstraints.HORIZONTAL;
		 equation.setBackground(SystemColor.info);
     this.add( equation, gbc );

		 gbc.gridx = 0;
     gbc.gridy = 2;
     gbc.gridwidth = 1;
     gbc.weightx = 0;
     gbc.weighty = 0;
     gbc.fill = GridBagConstraints.NONE;
     this.add( new JLabel( "Resultado"), gbc );

		 inputString.setText("");
		 gbc.weightx = 1;
     gbc.gridx = 1;
     gbc.fill = GridBagConstraints.HORIZONTAL;
     this.add( inputString, gbc );

     gbc.gridy = 3;
     gbc.gridx = 0;
     gbc.weightx = 0;
     gbc.anchor = GridBagConstraints.CENTER;
     gbc.fill = GridBagConstraints.NONE;
     jButton3.setText("Submit");
     jButton3.addActionListener(new MathTest_jButton3_actionAdapter(this));
     this.add( jButton3, gbc );

		 statusString.setText( "Status:  " );
		 gbc.gridy = 4;
		 gbc.gridx = 0;
		 gbc.gridwidth = 2;
		 gbc.weighty = 1;
		 gbc.anchor = GridBagConstraints.NORTHWEST;
		 gbc.fill = GridBagConstraints.VERTICAL;
		 this.add( statusString, gbc );

		 setEquation("exp(-3*s)");
			this.invalidate();
			this.validate();
   }

   void Applet_componentResized(ComponentEvent e) {
      sizecheck();
   }
}

class MathTest_jButton1_actionAdapter implements java.awt.event.ActionListener {
   MathTest adaptee;

   MathTest_jButton1_actionAdapter(MathTest adaptee) {
      this.adaptee = adaptee;
   }

   public void actionPerformed(ActionEvent e) {
      adaptee.Submit_actionPerformed(e);
   }
}

class MathTest_jButton2_actionAdapter implements java.awt.event.ActionListener {
   MathTest adaptee;

   MathTest_jButton2_actionAdapter(MathTest adaptee) {
      this.adaptee = adaptee;
   }

   public void actionPerformed(ActionEvent e) {
      adaptee.NextQuestion(e);
   }
}

class MathTest_jButton3_actionAdapter implements java.awt.event.ActionListener {
   MathTest adaptee;

   MathTest_jButton3_actionAdapter(MathTest adaptee) {
      this.adaptee = adaptee;
   }

   public void actionPerformed(ActionEvent e) {
      adaptee.Submit_Question2(e);
   }
}

class MathTest_this_componentAdapter extends java.awt.event.ComponentAdapter {
   MathTest adaptee;

   MathTest_this_componentAdapter(MathTest adaptee) {
      this.adaptee = adaptee;
   }

   public void componentResized(ComponentEvent e) {
      adaptee.Applet_componentResized(e);
   }
}
