import objectdraw.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Powers extends Controller implements ActionListener  {
  private static final int FONTSIZE = 18;
  private static final int INPUT_WIDTH = 4;

  // Recursive algorithm to compute powers
  public int power(int base, int n) {
    if (n==0) {
      return 1;    
    } else {
      return base*(power(base,n-1));    
    }
  }

  // Fast recursive algorithm to compute powers
  public int fastPower(int base, int n) {
    if (n == 0) {
      return 1;
    } else if (n % 2 == 0) {  // n is even
      return fastPower(base * base, n / 2);
    } else {                  // n is odd
      return base * fastPower(base, n - 1);
    }
  }

  private JTextField input;
  private JLabel l1, l0;
  private JTextField input2;
  private JButton goButton;
  private JLabel answer;

  public void begin() {
    l0 = new JLabel("power(");
    input = new JTextField("0", INPUT_WIDTH);
    l1 = new JLabel(", ");
    input2 = new JTextField("0", INPUT_WIDTH);
    answer = new JLabel(") = 0              ");
    goButton = new JButton("Go!");

    JPanel panel = new JPanel();

    input.setFont(new Font("System", 0, FONTSIZE));
    l0.setFont(new Font("System", 0, FONTSIZE));
    l1.setFont(new Font("System", 0, FONTSIZE));
    input2.setFont(new Font("System", 0, FONTSIZE));
    answer.setFont(new Font("System", 0, FONTSIZE));

    panel.add(l0);
    panel.add(input);
    panel.add(l1);
    panel.add(input2);
    panel.add(answer);

    JPanel buttonPanel = new JPanel();
    buttonPanel.add(goButton);

    Container contentPane = getContentPane();
    contentPane.add(panel, BorderLayout.NORTH);
    contentPane.add(buttonPanel, BorderLayout.CENTER);

    goButton.addActionListener(this);
    input.addActionListener(this);
    input2.addActionListener(this);
    validate();
  }

  // calculate power
  public void actionPerformed(ActionEvent e) {
    int base = Integer.parseInt(input.getText());
    int n = Integer.parseInt(input2.getText());
    answer.setText(") = " + power(base, n));
  }
}
