import java.applet.*;
import java.awt.*;
import java.util.StringTokenizer;
import graph.*;
import com.imsl.math.*;

public class ReflSimulator extends Applet {
    TextField[] parameters;
    Label[] paramLabels;
    TextField numCellsText, qminField, qmaxField, qpointsField, resolText;
    Panel instPanel;
    Checkbox smearedBox;
    Checkbox[] resolBoxes;
    CheckboxGroup cbg;
    Button calculate, showSLD;
    TextArea modelText, outputText;
     
    G2Dint graph;
    DataSet modelData, smearedData;
    Axis xaxis, yaxis;
    ReflectivityModel model;
    SLDPlot sldPlot;

    public void init() {
        Font font = new Font("TimesRoman",Font.PLAIN,12);
        graph = new G2Dint();
        graph.drawzero = false;
        graph.drawgrid = true;
        graph.borderTop = 20;                                                   
        graph.borderRight = 50;
        graph.setDataBackground(Color.white);
        graph.setBackground(Color.white);

        setLayout( new BorderLayout() );
        setBackground(Color.white);
        //Label title = new Label("Reflectivity simulator", Label.CENTER);
        Panel panel = new Panel();

        //title.setFont(new Font("TimesRoman",Font.PLAIN,20));

        //add("North", title);
        add("Center", panel);

        GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
        panel.setLayout(gridbag);
        c.ipadx = 5;
        c.weightx = 1.0;
        c.weighty = 1.0;
        c.gridwidth = 2;
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.fill = GridBagConstraints.BOTH;
        
        gridbag.setConstraints(graph,c);
        panel.add(graph);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx=0.0;
        c.weighty=0.0;
        c.gridheight=1;
        c.gridwidth=2;
        c.anchor = GridBagConstraints.CENTER;

        Label spacer1 = new Label(" ");
        gridbag.setConstraints(spacer1,c);
        panel.add(spacer1);


        c.gridwidth = GridBagConstraints.REMAINDER;
        c.anchor = GridBagConstraints.EAST;
        
        c.fill = GridBagConstraints.NONE;
        smearedBox = new Checkbox();
        smearedBox.setLabel("Smear data?");
        smearedBox.setFont(font);
        gridbag.setConstraints(smearedBox,c);
        panel.add(smearedBox);
        smearedBox.enable(false);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.anchor = GridBagConstraints.NORTH;
        Panel paramPanel = new Panel();
        paramPanel.setLayout(new GridLayout(5,2));

        //initialize the values in the fields
        model = new Refl5a();
        double[] paramValues = {0.0,0.0,0.0,0.0};
        String[] paramText = {"Fronting, Real","Imag",
                              "Backing, Real","Imag"};
        parameters = new TextField[4];
        paramLabels = new Label[4];
        for(int i=0;i<4;i++) {
                paramLabels[i] = new Label(paramText[i], Label.RIGHT);
            paramLabels[i].setFont(font);
            paramPanel.add(paramLabels[i]);
            parameters[i] = new TextField(String.valueOf(paramValues[i]),8);
            parameters[i].setFont(font);
            paramPanel.add(parameters[i]);
        }
        Label numCellsLabel = new Label("Num cells: ",Label.RIGHT);
        numCellsLabel.setFont(font);
        paramPanel.add(numCellsLabel);
        numCellsText = new TextField(String.valueOf(1),8);
        numCellsText.setFont(font);
        paramPanel.add(numCellsText);

        Label qmin = new Label("Qmin: ", Label.RIGHT);
        Label qmax = new Label("Qmax: ", Label.RIGHT);
        Label qpoints = new Label("# Points: ", Label.RIGHT);

        resolText = new TextField(String.valueOf(0.0),8);
        resolText.setFont(font);
        Label resolLabel = new Label("Resolution", Label.RIGHT);
        resolLabel.setFont(font);
        
        cbg = new CheckboxGroup();
        resolBoxes = new Checkbox[2];
        resolBoxes[0] = new Checkbox("DeltaQ", cbg, true);
        resolBoxes[1] = new Checkbox("DeltaQ/Q", cbg, false);
        resolBoxes[0].setFont(font);
        resolBoxes[1].setFont(font);

        Label spacer2 = new Label(" "); 
        Label spacer3 = new Label(" "); 

        qmin.setFont(font);
        qmax.setFont(font);
        qpoints.setFont(font);
        qminField = new TextField("0.001",8);
        qmaxField = new TextField("0.1",8);
        qpointsField = new TextField("200",8);
        qminField.setFont(font);
        qmaxField.setFont(font);
        qpointsField.setFont(font);
        
        Panel qPanel = new Panel();
        qPanel.setLayout(new GridLayout(3,2));
        qPanel.add(qmin);
        qPanel.add(qminField);
        qPanel.add(qmax);
        qPanel.add(qmaxField);
        qPanel.add(qpoints);
        qPanel.add(qpointsField);
        
        instPanel = new Panel();
        instPanel.setLayout(new GridLayout(3,2));
        instPanel.add(resolLabel);
        instPanel.add(resolText);
        instPanel.add(spacer1);
        instPanel.add(resolBoxes[0]);
        instPanel.add(spacer2);
        instPanel.add(resolBoxes[1]);

        c.gridwidth = 1;
        c.anchor = GridBagConstraints.NORTH;
        gridbag.setConstraints(paramPanel,c);
        panel.add(paramPanel);
        
        gridbag.setConstraints(qPanel,c);
        panel.add(qPanel);

        c.gridwidth = GridBagConstraints.REMAINDER;
        gridbag.setConstraints(instPanel,c);
        panel.add(instPanel);
        instPanel.enable(false);

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridwidth = GridBagConstraints.REMAINDER;
        calculate = new Button("Calculate");
        calculate.setFont(font);
        gridbag.setConstraints(calculate,c);
        panel.add(calculate);

        showSLD = new Button("Show SLD Profile");
        showSLD.setFont(font);
        gridbag.setConstraints(showSLD,c);
        panel.add(showSLD);

        modelText = new TextArea("1.0 0.0 1000.0",10,8);
        modelText.setFont(new Font("Courier",Font.PLAIN,12));
        outputText = new TextArea(10,8);
        outputText.setFont(new Font("Courier",Font.PLAIN,12));
        
        c.gridwidth = 1;
        gridbag.setConstraints(modelText,c);
        panel.add(modelText);

        c.gridwidth = GridBagConstraints.REMAINDER;
        gridbag.setConstraints(outputText,c);
        panel.add(outputText);

        xaxis = graph.createXAxis();
        xaxis.setTitleText("Q (A^{-1})");
        xaxis.setTitleFont(new Font("TimesRoman",Font.PLAIN,15));
        xaxis.setLabelFont(new Font("Helvetica",Font.PLAIN,12));

        yaxis = graph.createYAxis();
        yaxis.setTitleText("log(Reflectivity)");
        yaxis.setTitleFont(new Font("TimesRoman",Font.PLAIN,15));
        yaxis.setLabelFont(new Font("Helvetica",Font.PLAIN,12));

        modelData = new DataSet();
        modelData.linecolor = Color.black;
        smearedData = new DataSet();
        smearedData.linecolor = Color.red;
 
        xaxis.attachDataSet(modelData);
        xaxis.attachDataSet(smearedData);
        yaxis.attachDataSet(modelData);
        yaxis.attachDataSet(smearedData);
        graph.attachDataSet(modelData);
        graph.attachDataSet(smearedData);

        sldPlot = new SLDPlot();

        updatePlot();

    }

    public void updatePlot() {
        int i, qpoints;
        int count = 0;
        double qmin, qmax, qinc, qtemp, x;
        double resolValue = 0.001;
        int resolType = 0;
        boolean error = false;

        double paramValues[] = new double[4];
        boolean state = smearedBox.getState();

        if(state) {
            try {
                resolValue = Double.valueOf(resolText.getText()).doubleValue();
            } catch(Exception e) {
                this.showStatus("Error with resolution value!");
                System.out.println("Error with resolution value!");
                return;
            }
            String whichResol = cbg.getCurrent().getLabel();
            if(whichResol.equalsIgnoreCase("DeltaQ")) {
                resolType = 0;
            } else { 
                resolType = 1;
            }
            model.setResolution(resolValue);
        }

        try {
            qmin = Double.valueOf(qminField.getText()).doubleValue();
        } catch(Exception e) {
            this.showStatus("Error with qmin!");
            System.out.println("qmin error "+e.getMessage());
            return;
        }
        if(qmin <= 0.0) qmin = 0.0001;

        try {
            qmax = Double.valueOf(qmaxField.getText()).doubleValue();
        } catch(Exception e) {
            this.showStatus("Error with qmax!");
            System.out.println("qmax error "+e.getMessage());
            return;
        }
        if (qmax <= 0.0) qmax = 1.0;

        try {
            qpoints = Integer.parseInt(qpointsField.getText());
        } catch(Exception e) {
            this.showStatus("Error with number of points!");
            System.out.println("Number of points error "+e.getMessage());
            return;
        }

        if (qmax < qmin) {
            qtemp = qmin;
            qmin = qmax;
            qmax = qtemp;
            qminField.setText(String.valueOf(qmin));
            qmaxField.setText(String.valueOf(qmax));
        }
        if (Math.abs(qmax-qmin) <= 0.001) {
            qmin = 0.001;
            qmax = 0.2;
            qminField.setText(String.valueOf(qmin));
            qmaxField.setText(String.valueOf(qmax));
        }
        if (qpoints <= 0) {
            qpoints = 300;
            qpointsField.setText(String.valueOf(qpoints));
        }
        qinc = (qmax-qmin)/(double)qpoints;
        
        for(i=0;i<4;i++) {
            try {
                paramValues[i] = 
                    1.0e-6*Double.valueOf(parameters[i].getText()).doubleValue();
            } catch(Exception e) {
                this.showStatus("Error with parameter "+i+"!");
                System.out.println("Parameter error "+e.getMessage());
                return;
            }
        }

        int numCells = 1;
        try {
            numCells = (int)(Double.valueOf(numCellsText.getText()).doubleValue());
        } catch(Exception e) {
            this.showStatus("Error with number of cells!");
            System.out.println("Number of cells error: "+e.getMessage());
            return;
        }
        if(numCells < 1){
            numCells = 1;
            numCellsText.setText(String.valueOf(numCells));
        }

        model.setFronting(new Complex(paramValues[0],paramValues[1]));
        model.setBacking(new Complex(paramValues[2],paramValues[3]));

        //get model from text field
        String modelString = modelText.getText();
        StringTokenizer st = new StringTokenizer(modelString);
        int numTokens = st.countTokens();
        if((numTokens%3 != 0)||(numTokens < 3)) {
            this.showStatus("Error with model text!");
            System.out.println("Problem with model text.");
            return;
        }
        int numLayersCell = numTokens/3;
        int numLayers = numLayersCell*numCells;

        double[] deltaZ = new double[numLayers];
        Complex[] rho = new Complex[numLayers];
        double[] deltaZCell = new double[numLayersCell];
        Complex[] rhoCell = new Complex[numLayersCell];

        for(i=0;i<numLayersCell;i++) {
           rhoCell[i] = new Complex(
                   1.0e-6*Double.valueOf(st.nextToken()).doubleValue(),
                   1.0e-6*Double.valueOf(st.nextToken()).doubleValue()) ;
           deltaZCell[i] = Double.valueOf(st.nextToken()).doubleValue();
        }

        for(i=0;i<numLayers;i++) {
           rho[i] = new Complex(rhoCell[i%numLayersCell]);
           deltaZ[i] = deltaZCell[i%numLayersCell];
        }

        model.setDeltaZ(deltaZ);
        model.setRho(rho);

        double d[] = new double[2*qpoints];
        double d2[] = new double[2*qpoints];
        Complex reflectivity = new Complex();
 
        this.showStatus("Calculating points!");
 
        for(i=0;i<qpoints;i++) {
            x = qmin + (double)i*qinc;
            d[count] = x;
            try {
                if(state) {
                    d2[count] = x;
                    d2[count+1] = model.getSmearedReflectivity(x, resolType);
                    d2[count+1] = SpecialFunction.log10(d2[count+1]);
                }
                reflectivity = model.getReflectivity(x);
                d[count+1] = reflectivity.real()*reflectivity.real() +
                    reflectivity.imag()*reflectivity.imag();
                d[count+1] = SpecialFunction.log10(d[count+1]);
                count += 2;
            } catch(Exception e) {error = true;}
        }

        if(count <= 2) {
            this.showStatus("Error NO POINTS to PLOT!");
            System.out.println("Error NO POINTS to PLOT!");
            return;
        } else
        if( error ) {
            this.showStatus("Error while Calculating points!");
            System.out.println("Error while calculating points!");
        }
        
        modelData.deleteData();
        smearedData.deleteData();

        try {
              modelData.append(d,count/2);
              smearedData.append(d2,count/2);
        } catch(Exception e) {
            this.showStatus("Error while appending data!");
            System.out.println("Error while appending data!");
            return;
        }

        sldPlot.setModel(model);
        sldPlot.updatePlot();

        // put data in output textarea
        String outputData = "";
        int point = 0;
        for(i=0;i<count/2;i++) {
           point = 2*i;
           outputData +=(new Format("%10.5f").format(d[point]))
                        +" "
                        +(new Format("%10.5G").format(Math.pow(10,d[point+1])))
                        +"\n";
        }
        outputText.setText(outputData);

        graph.repaint();

        this.showStatus("Done Calculating!");
        
    }

    public boolean action(Event e, Object a) {
        if (e.target instanceof Button) {
            if (calculate.equals(e.target)) {
                updatePlot();
                return true;
            } else {
                if (sldPlot.isVisible()) {
                   sldPlot.hide();
                   showSLD.setLabel("Show SLD Profile");
                } else {
                   sldPlot.show();
                   showSLD.setLabel("Hide SLD Profile");
                }
            }
        }
        if (e.target instanceof Checkbox) {
            boolean state = ((Checkbox)e.target).getState();
            instPanel.show(state);
            updatePlot();
            return true;
        } 
        if (e.target instanceof TextField) {
            updatePlot();
            return true;
        }
        return false;
    }

}

