import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;

public class CalculatorPanel extends JPanel implements ICalculatorView
{
    private CalculatorModel myModel;
    private JTextField myTextDisplay;

    private JPanel myNumberPanel;
    private JPanel myFunctionPanel;
    private boolean isStandardView;
    
    /**
     * Create a view with a model
     * @param model is the model for this view
     */
    public CalculatorPanel(CalculatorModel model)
    {
	setLayout(new BorderLayout());

        myModel = model;
	myNumberPanel = new NumberButtonPanel(model);
        myFunctionPanel = new FunctionButtonPanel(model);
        
	myTextDisplay = new JTextField(20);
        myTextDisplay.setHorizontalAlignment(JTextField.RIGHT);
        myTextDisplay.setFont(CalcButton.getBigFont());
        myTextDisplay.setEditable(false);
        myTextDisplay.setBackground(java.awt.Color.WHITE);

        
        JPanel sub = new JPanel(new BorderLayout());
        sub.add(myTextDisplay, BorderLayout.NORTH);
        sub.add(getClearButtons(myModel), BorderLayout.SOUTH);
        add(sub,BorderLayout.NORTH);
	add(myNumberPanel, BorderLayout.CENTER);
	isStandardView = true;
        myModel.setView(this); 
    }

    public void changeView()
    {
	if (isStandardView){
	    isStandardView = false;
	    remove(myNumberPanel);
	    add(myNumberPanel, BorderLayout.EAST); 
	    add(myFunctionPanel, BorderLayout.WEST);    
	}
	else{
	    isStandardView = true;
	    remove(myFunctionPanel);
	    remove(myNumberPanel);
	    add(myNumberPanel, BorderLayout.CENTER);
	}
	validate();
    }

    private JPanel getClearButtons(final CalculatorModel model)
    {
        JPanel panel = new JPanel(new GridLayout(1,4));
        JButton b1 = new JButton();
        JButton b2 = new JButton();
        JButton clearEntry = new CalcButton("CE");
        JButton clear = new CalcButton("C");
        clearEntry.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e)
                {
                    model.clearEntry();
                }                
            });
        clear.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e)
                {
                    model.clear();
                }                
            });
        panel.add(b1);
        panel.add(b2);
        panel.add(clearEntry);
        panel.add(clear);
        return panel;
    }

    public void display(String s)
    {
        myTextDisplay.setText(s);
    }
}
