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.*;
import javax.swing.border.*;


public class FunctionGrapher extends JApplet {
    boolean isStandalone = false;
    JButton JButton1 = new JButton();
    Box box1;
    Box box2;
    Box box4;
    Box box5;
    Box box6;
    Box box7;
    Box box8;
    Box box9;
    Box xbox;
    Box ybox;
    Box tgbox1;
    Box tgbox2;
    Box xtgbox;
    Box ytgbox;
    JTextField mapleInput = new JTextField();
    ImagePanel imagePanel1 = new ImagePanel();
    Border border1;
    JPanel func = new JPanel();
    JPanel tangent = new JPanel();
    JPanel derivative = new JPanel();

    String sUser;
    String sPassword;
    String sHost;
    int    iPort;

    Border border2;
    TitledBorder titledBorder1;
    Border border3;
    TitledBorder titledBorder2;
    Border border4;
    TitledBorder titledBorder3;
    Border border5;
    Border border6;
    TitledBorder titledBorder4;
    JCheckBox xCheckBox = new JCheckBox();
    JCheckBox yCheckBox = new JCheckBox();
    JTextField xMin = new JTextField();
    JTextField xMax = new JTextField();
    JTextField yMin = new JTextField();
    JTextField yMax = new JTextField();
    JCheckBox displayDerivative = new JCheckBox();
    JTextField outDerivative = new JTextField();
    JTextField tgEquation = new JTextField();
    JCheckBox tgDisplay = new JCheckBox();
    JLabel xtgLabel = new JLabel();
    JLabel ytgLabel = new JLabel();
    JTextField xtgInput = new JTextField();
    JTextField ytgOutput = new JTextField();
    Component component1;

    //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 FunctionGrapher() {
    }

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

            sHost = this.getParameter( "host", sDocHost );
            //host = "localhost";
        } catch (Exception e) { e.printStackTrace(); }
        try {
            iPort = Integer.parseInt(this.getParameter("port", "14444"));
        } catch (Exception e) { e.printStackTrace(); }

        try {
            iPort = Integer.parseInt(this.getParameter("port", "14444"));
        } catch (Exception e) { e.printStackTrace(); }

        try {
            sUser = this.getParameter("usuário", "cliente");
        } catch (Exception e) { e.printStackTrace(); }

        try {
            sPassword = this.getParameter("senha", "demopass");
        } catch (Exception e) { e.printStackTrace(); }

        try {
            jbInit();
            //myInit();
            //sizecheck();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }   

    //Component initialization
    private void jbInit() throws Exception {
        box1 = Box.createHorizontalBox();
        box2 = Box.createVerticalBox();
        box4 = Box.createVerticalBox();
        box5 = Box.createVerticalBox();
        box6 = Box.createVerticalBox();
        box7 = Box.createVerticalBox();
        box8 = Box.createVerticalBox();
        box9 = Box.createVerticalBox();
        xbox = Box.createHorizontalBox();
        ybox = Box.createHorizontalBox();
        tgbox1 = Box.createHorizontalBox();
        tgbox2 = Box.createVerticalBox();
        xtgbox = Box.createHorizontalBox();
        ytgbox = Box.createHorizontalBox();
        border1 = BorderFactory.createLineBorder(Color.white,1);
        border2 = BorderFactory.createLineBorder(SystemColor.controlText,1);
        titledBorder1 = new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlText,1),"Função");
        border3 = BorderFactory.createLineBorder(SystemColor.controlText,1);
        titledBorder2 = new TitledBorder(BorderFactory.createLineBorder(SystemColor.controlText,1),"Tangente");
        border4 = BorderFactory.createLineBorder(SystemColor.controlText,1);
        titledBorder3 = new TitledBorder(border4,"Derivada");
        border5 = BorderFactory.createCompoundBorder(titledBorder1,BorderFactory.createEmptyBorder(0,2,0,0));
        border6 = BorderFactory.createLineBorder(SystemColor.controlText,1);
        titledBorder4 = new TitledBorder(border6,"Função");
        component1 = Box.createGlue();
        JButton1.setText("Plotar");
        JButton1.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                JButton1_actionPerformed(e);
            }
        });
        this.setSize(new Dimension(400,400));
        mapleInput.setBorder(null);
        mapleInput.setMinimumSize(new Dimension(160, 21));
        mapleInput.setPreferredSize(new Dimension(160, 21));
        mapleInput.setText("");
        imagePanel1.setOpaque(false);
        imagePanel1.setPreferredSize(new Dimension(220, 220));
        func.setBorder(titledBorder4);
        tangent.setBorder(titledBorder2);
        derivative.setBorder(titledBorder3);

        xCheckBox.setSelected(true);
        xCheckBox.setText("x:");
        xCheckBox.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                xCheckBox_actionPerformed(e);
            }
        });
        yCheckBox.setSelected(true);
        yCheckBox.setText("y:");
        yCheckBox.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                yCheckBox_actionPerformed(e);
            }
        });
        displayDerivative.setText("Mostrar");
        displayDerivative.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                displayDerivative_actionPerformed(e);
            }
        });
        outDerivative.setMinimumSize(new Dimension(160, 21));
        outDerivative.setPreferredSize(new Dimension(160, 21));
        outDerivative.setEditable(false);
        tgEquation.setMinimumSize(new Dimension(160, 21));
        tgEquation.setPreferredSize(new Dimension(160, 21));
        tgEquation.setEditable(false);
        tgDisplay.setText("display");
        tgDisplay.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                tgDisplay_actionPerformed(e);
            }
        });
        xtgLabel.setText("x:");
        ytgLabel.setText("y:");
        ytgOutput.setEditable(false);
        xMin.setText("-10");
        xMax.setText("10");
        yMax.setText("-5");
        yMin.setText("5");
        xtgInput.setText("0");
        box4.add(box1,null);
        box5.add(tangent,null);
        box4.add(box5, null);
        box6.add(derivative,null);
        box4.add(box6, null);
        box1.add(func, null);
        func.add(box7,null);
        xbox.add(xCheckBox, null);
        xbox.add(xMin, null);
        xbox.add(xMax, null);
        box7.add(mapleInput, null);
        box7.add(component1, null);
        box7.add(xbox,null);
        box7.add(ybox, null);
        ybox.add(yCheckBox, null);
        ybox.add(yMax, null);
        ybox.add(yMin, null);
        tangent.add(box8, null);
        box8.add(tgbox1, null);
        box8.add(tgEquation, null);
        tgbox2.add(xtgbox, null);
        xtgbox.add(xtgLabel, null);
        xtgbox.add(xtgInput, null);
        tgbox2.add(ytgbox, null);
        ytgbox.add(ytgLabel, null);
        ytgbox.add(ytgOutput, null);
        tgbox1.add(tgDisplay, null);
        tgbox1.add(tgbox2, null);
        derivative.add(box9, null);
        box9.add(displayDerivative, null);
        box9.add(outDerivative, null);
        box2.add(imagePanel1, null);
        this.getContentPane().add(box2, BorderLayout.WEST);
        this.getContentPane().add(box4, BorderLayout.EAST);
        this.getContentPane().add(JButton1, BorderLayout.SOUTH);
    }

    //Start the applet
    public void start() {
    }

    //Stop the applet
    public void stop() {
    }

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

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

    //Get parameter info
    public String[][] getParameterInfo() {
        return null;
    }

    //static initializer for setting look & feel
    static {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        }
        catch(Exception e) {
        }
    }

    void JButton1_actionPerformed(ActionEvent e) {
        do_something(e);
    }

    void do_something(ActionEvent e) {
        String to_plot = " ";

        if (tgDisplay.isSelected()) {
            MapleStatement statement = new MapleStatement( sHost, iPort, sUser, sPassword);

            try {
                // Obtain the slope of the function at point a
                String pt_a = xtgInput.getText();
                String curve = mapleInput.getText();

                String[] request = new String[4];
                request[0] = "slope  := eval(diff(" + curve + ",x), x = " + pt_a + "):";
                request[1] = "yValue := eval(" + curve + ", x = " + pt_a + "):";
                request[2] = "slope";
                request[3] = "slope*(x - (" + pt_a + ")) + yValue";
                String[] response = statement.execute(request);

                ytgOutput.setText(response[2]);
                tgEquation.setText("y = " + response[3]);

                to_plot = to_plot + ", " + response[3];
            } catch ( MapleStatementException ex2) {
                System.out.println("Erro de sintaxe: " + ex2.toString());
            } catch ( MapleException ex1) {
                System.out.println("Erro ao conectar no servidor: " + ex1.toString());
            }
        }

        if (displayDerivative.isSelected()) {
            MapleStatement statement = new MapleStatement( sHost, iPort, sUser, sPassword);

            try {
                String derivative = statement.execute( "diff(" + mapleInput.getText() + ",x)");
                outDerivative.setText(derivative);

                to_plot = to_plot + ", " + derivative;
            } catch ( MapleStatementException ex2) {
                System.out.println("Erro de sintaxe: " + ex2.toString());
            } catch ( MapleException ex1) {
                System.out.println("Erro ao conectar no servidor: " + ex1.toString());
            }
        }

        // And now do the plot
        // Blank the current image
        imagePanel1.setImage(null);
        imagePanel1.repaint(0);

        // Create an empty plot request
        // sync_host_and_user(); // no clue!?
        MapleImage2DPlot mip = new MapleImage2DPlot( sHost, iPort, sUser, sPassword );

        // Fill in the plot information
        mip.setType( MapleImage2DPlot.GIF );

        // Set the resultant plot width to match the ImagePanel component
        mip.setDimensions( imagePanel1.getWidth(), imagePanel1.getHeight());

        // Fill in some plot stuff
        mip.setFunction( "[" + mapleInput.getText() + to_plot + "]" );
        if (xCheckBox.isEnabled()) {
            mip.setDomain( "x", xMin.getText(), xMax.getText());
        } else {
            mip.setDomain( "x", -10, 10);
        }
        if (yCheckBox.isEnabled()) {
            mip.setRange( "y", yMin.getText(), yMax.getText());
        } else {
            mip.setRange( "y", -2, 2);
        }

        try {
            Image img = mip.getPlot();
            if (img != null ) {
                imagePanel1.setImage( img );
                imagePanel1.repaint();
            }
        } catch( Exception ex ) {
            System.out.println("Plot generation exception: " + ex.toString());
        }
    }

    void xCheckBox_actionPerformed(ActionEvent e) {
        do_something(e);
    }

    void yCheckBox_actionPerformed(ActionEvent e) {
        do_something(e);
    }

    void tgDisplay_actionPerformed(ActionEvent e) {
        do_something(e);
    }

    void displayDerivative_actionPerformed(ActionEvent e) {
        do_something(e);
    }
}
