package com.marinilli.b2.c7.deploylet;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import javax.swing.border.*;

/**
 * Chapter 7 - The example account applet
 *
 * @author Mauro Marinilli
 * @version 1.0
 */
public class AccountApplet extends ClientDeploylet {
  JButton calcButton = new JButton();
  JTextField hoursTextField = new JTextField(4);
  JTextField hpdTextField = new JTextField(4);
  JLabel resultLabel = new JLabel();

  /**Construct the applet*/
  public AccountApplet() {
  }

  /**Initialize the applet*/
  public void initApplication() {
    JPanel mainPanel = new JPanel();
    JPanel southPanel = new JPanel();
    Box box1 = Box.createHorizontalBox();
    Box box2 = Box.createHorizontalBox();
    Box box3 = Box.createVerticalBox();
    JLabel hpdLabel = new JLabel();
    JLabel hoursLabel = new JLabel();
    setSize(new Dimension(400,300));
    calcButton.setText("execute");
    calcButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(ActionEvent e) {
        calculate(e);
      }
    });
    hoursTextField.setText("0");
    hoursLabel.setText("working hours total amount");
    resultLabel.setBorder(
        BorderFactory.createCompoundBorder(
              new TitledBorder(
                  BorderFactory.createEtchedBorder(
                        Color.white,
                        new Color(142, 142, 142)),"Total Result "),
                        BorderFactory.createEmptyBorder(0,20,0,20)
                        ));
    resultLabel.setPreferredSize(new Dimension(290,40));
    resultLabel.setText("---");
    box2.add(hoursTextField);
    box2.add(hoursLabel, null);
    hpdTextField.setText("0");
    hpdLabel.setText("working hours per day");
    box1.add(hpdTextField);
    box1.add(hpdLabel, null);
    this.getContentPane().add(mainPanel, BorderLayout.CENTER);
    mainPanel.add(resultLabel, null);
    box3.add(box1);
    box3.add(box2);
    mainPanel.add(box3, null);
    this.getContentPane().add(southPanel, BorderLayout.SOUTH);
    southPanel.add(calcButton, null);
  }

  /**Start the applet*/
  public void startApplication() {
    log("account applet started");
  }

  /**
   * throws an exception
   */
  void calculate(ActionEvent e) {
    try {
      // hopefully we'll get an exception here
      int hours = Integer.valueOf(hoursTextField.getText()).intValue();
      int hpd   = Integer.valueOf(hpdTextField.getText()).intValue();
      resultLabel.setText(hours / hpd + " days");
    }
    catch (Exception ex) {
      log(ex);
    }
  }

}