package com.maplesoft.maplenet.tutorial;

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

import javax.swing.*;

import com.maplesoft.client.mathmlEquation;
import com.maplesoft.client.mathmlEditEquation;
import com.maplesoft.client.MapleToMathML;


public class StackTestApplet extends Applet {
   boolean isStandalone = false;

   String host;
   int port;
   String user;
   String password;
   MapleToMathML convertor; 

   TextField expressionString = new TextField();
   Button pushButton = new Button();
   Button popButton  = new Button();

   mathmlEquation mathml    = new mathmlEquation();
   mathmlEquation stacksize = 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 StackTestApplet() {
   }

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

         host = this.getParameter( "host", sDocHost );
      }
      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();
      }
      catch(Exception e) {
         e.printStackTrace();
      }

      convertor = new MapleToMathML( host, port, user, password );
   }

   private void myInit() {
      this.setSize( 400, 400 );
      mathml.setControls( true );
      mathml.registerControls( true );
      mathml.allow_cut = true;

      stacksize.setControls( true );
      stacksize.registerControls( true );
      stacksize.allow_cut = true;

   }

   //Component initialization
   private void jbInit() throws Exception {
      this.setLayout(null);
      expressionString.setBackground(Color.white);
      expressionString.setBounds(new Rectangle(112, 51, 137, 25));
      expressionString.setFont(new java.awt.Font("Dialog", 0, 14));
      expressionString.addKeyListener(new java.awt.event.KeyAdapter() {

         public void keyTyped(KeyEvent e) {
            expressionString_keyTyped(e);
         }
      });

      pushButton.setBounds(new Rectangle(326, 50, 46, 30));
      pushButton.setLabel("Push");
      pushButton.addActionListener(new StackTestApplet_pushButton_actionAdapter(this));

      popButton.setBounds(new Rectangle(271, 50, 46, 30));
      popButton.setLabel("Pop");
      popButton.addActionListener(new StackTestApplet_popButton_actionAdapter(this));

      this.setBackground(SystemColor.info);
      this.addKeyListener(new java.awt.event.KeyAdapter() {

         public void keyTyped(KeyEvent e) {
            this_keyTyped(e);
         }
      });
      this.addComponentListener(new java.awt.event.ComponentAdapter() {

         public void componentResized(ComponentEvent e) {
            this_componentResized(e);
         }
      });

      mathml.initBG(SystemColor.info);
      mathml.setBackground(SystemColor.info);
      mathml.setBounds(new Rectangle(20, 190, 350, 100));
      mathml.setPrefix("");
      mathml.setLocation( 20, 190 );
      mathml.setSize( 350, 100 );
      mathml.setLinebreak( true );
      mathml.setDrawBorder( true );

      stacksize.initBG(SystemColor.info);
      stacksize.setBackground(SystemColor.info);
      stacksize.setBounds(new Rectangle(20, 140, 350, 40));
      stacksize.setPrefix("");
      stacksize.setLocation( 20, 140 );
      stacksize.setSize( 350, 40 );
      stacksize.setLinebreak( true );
      stacksize.setDrawBorder( true );

      this.add(expressionString, null);
      this.add(pushButton, null);
      this.add(popButton, null);

      this.add(mathml, null);
      this.add(stacksize, null);
   }

   //Start the applet
   public void start() {
      try {
         convertor.getLock();
         convertor.execute("[assign(s,SimpleStack())]", 2);
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }

   //Stop the applet
   public void stop() {
      try {
         convertor.releaseLock();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }

   //Destroy the applet
   public void destroy() {
   }

   //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;
   }

   //Main method
   public static void main(String[] args) {
      StackTestApplet applet = new StackTestApplet();
      applet.isStandalone = true;
      Frame frame;
      frame = new Frame();
      frame.setTitle("Applet Frame");
      frame.add(applet, BorderLayout.CENTER);

      applet.init();
      applet.start();

      frame.setSize(600,420);
      Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
      frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
      frame.setVisible(true);

   }

   void do_something( String sInput ) {
      String[] saInput  = new String[2];
      String[] saOutput = new String[2];

      saInput[0] = sInput;
      saInput[1] = "sprintf(\"Number of items on stack: %d\",s:-depth())";

      System.out.println("Tente   :"+host+":"+port+"  usuário="+user);
      System.out.println("Input :"+saInput[0] + " " + saInput[1]);
      try {
         // sOutput = convertor.execute( sInput + " = " + tInput , 2 );
         saOutput = convertor.execute( saInput , 2 );
         System.out.println("Saída :"+saOutput[0]+ " " + saOutput[1]);
         mathml.setEquation( saOutput[0] );
         stacksize.setEquation( saOutput[1] );
      } catch( Exception ex ) {
         System.out.println("Erro de conversão :" + ex.toString() );
         mathml.setEquation( "<math><mi>???</mi></math>" );
         stacksize.setEquation( "<math><mi>???</mi></math>" );
      }
      expressionString.requestFocus();
      expressionString.selectAll();
      expressionString.setText("");
      repaint();
   }

   void do_push_something() {
      do_something("s:-push(" +expressionString.getText() + ")");
   }

   void do_pop_something() {
      do_something("`if`(s:-depth()>0,s:-pop(),\"Stack is empty\")");
   }

   void resize_the_applet() {
      int w = getWidth();
      int h = getHeight();
      int x;
      int y;
      int xw;
      int yh;

      System.out.println( "Resizing "+w+","+h);

      y  = 50;
      yh = 25; 

      xw = 45;
      x = w - 15 - xw;
      pushButton.setBounds( new Rectangle( x, y, xw, yh));

      popButton.setBounds( new Rectangle( x, y, xw, yh));

      xw = x - 85 - 5;
      if(xw < 0) xw = 10;
      x  = 85;
      expressionString.setBounds( new Rectangle( x, y, xw, yh));

      mathml.setBounds( new Rectangle( 20, 150, w-40, h-150-10) );
   }

   void pushButton_actionPerformed(ActionEvent e) {
      do_push_something();
   }

   void popButton_actionPerformed(ActionEvent e) {
      do_pop_something();
   }

   void this_componentResized(ComponentEvent e) {
      resize_the_applet();
   }

   void this_keyTyped(KeyEvent e) {
      if( e.getKeyCode() == KeyEvent.VK_ENTER) {
         do_push_something();
      }
   }

   void expressionString_keyTyped(KeyEvent e) {
      if( e.getKeyCode() == KeyEvent.VK_ENTER) {
         do_push_something();
      }
   }
}

class StackTestApplet_pushButton_actionAdapter implements java.awt.event.ActionListener {
   StackTestApplet adaptee;

   StackTestApplet_pushButton_actionAdapter(StackTestApplet adaptee) {
      this.adaptee = adaptee;
   }

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

class StackTestApplet_popButton_actionAdapter implements java.awt.event.ActionListener {
   StackTestApplet adaptee;

   StackTestApplet_popButton_actionAdapter(StackTestApplet adaptee) {
      this.adaptee = adaptee;
   }

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