/*
 * Created on Sep 8, 2003
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package AppletInterface;

import amber.type.server.*;
import amber.server.panel.*;
import amber.server.component.*;
import amber.server.application.ApplicationInterface;
import amber.server.exception.*;
import amber.awt.event.*;

import java.awt.*;
import java.awt.event.*;
import DataClasses.*;

/**
  * This class handles the requirements for the specific manipulation of panels within
  * specific applications. In a lot of ways this class functions very similarly to the
  * ApplicationInterface class.
  * This is the overall intelligence for this particular panel.
  *
  * @author Insert your name here
  * @version 1.0.0
  * @see amber.server.panel.BaseFrame
*/
/**
 * @author student
 *
 * This class is being used for displaying information about a selected owned stock.
 * 
 */
public class OwnershipFrame
	extends BaseFrame
	implements ComponentWindowListener, ActionListener {
	/**
	  * Declare the components used in this frame.
	*/
	private LabelHandler lblMain = new LabelHandler(getParentApplication());
	private LabelHandler lblStockName =
		new LabelHandler(getParentApplication());
	private LabelHandler lblStockCode =
		new LabelHandler(getParentApplication());
	private LabelHandler lblHigh = new LabelHandler(getParentApplication());
	private LabelHandler lblLow = new LabelHandler(getParentApplication());
	private LabelHandler lblTotalQty = new LabelHandler(getParentApplication());
	private LabelHandler lblTotalCost =
		new LabelHandler(getParentApplication());
	private LabelHandler lblAvgCost = new LabelHandler(getParentApplication());
	private LabelHandler lblLastPurchaseQty =
		new LabelHandler(getParentApplication());
	private LabelHandler lblLastPurchaseAmount =
		new LabelHandler(getParentApplication());
	private LabelHandler lblLastPurchaseRate =
		new LabelHandler(getParentApplication());
	private LabelHandler lblDateLastPurchased =
		new LabelHandler(getParentApplication());
	private FloatButtonHandler btnOk =
		new FloatButtonHandler(getParentApplication());

	public final int FRAMEWIDTH = 400;
	public final int FRAMEHEIGHT = 500;

	private Font level1 = new Font("Arial", Font.BOLD, 14);
	private Font level2 = new Font("Arial", Font.ITALIC, 14);

	private User_Data userdata = getStockTradingApplication().getUser();
	private Stock_Data[] totalstocks = getStockTradingApplication().getStocks();
	private StockOwnership_Data[] owned = userdata.getStocksOwned();

	private String index;

	/**
	 * This is the constructor for OwnershipFrame.java
	 */
	public OwnershipFrame() {
		super();
		defineComponents();
	}

	/**
	  * The initialising constructor.
	  * @param appHandler The handle to the main ApplicationInterface which
	  * handles the functions of the overall application.
	*/
	public OwnershipFrame(ApplicationInterface appHandler) {
		super(appHandler);
		defineComponents();
	}

	/**
	  * The initialising constructor.
	  * @param appHandler The handle to the main ApplicationInterface which
	  * handles the functions of the overall application.
	*/
	public OwnershipFrame(ApplicationInterface appHandler, String i) {
		super(appHandler);
		this.index = i;
		defineComponents();
	}

	/**
	  * The initialising constructor.
	  * @param id The int containing the id of the corresponding remote component
	  * residing on the browser.
	  * @param appHandler The handle to the main ApplicationInterface which
	  * handles the functions of the overall application.
	*/
	public OwnershipFrame(int id, ApplicationInterface appHandler) {
		super(id, appHandler);
		defineComponents();
	}

	/**
		* This function would normally never need to be called, but is required
		* to be defined as it is called internally.
		* Its specific purpose is to set the controls to a known state once
		* they are created.
	*/
	public void fillControls() {
	}

	/**
	  * This function determines if the panel can be closed.
	  * The derived panels must determine if this panel can close. If this is
	  * not possible the function should return false.
	  * @return boolean false if it is not possible to close this panel.
	*/
	public boolean canClose() {
		return true;
	}

	/**
	  * This function is called to save any required information in the panel.
	  * This function is called externally when another panel wishes to take
	  * over the base panel or when closing the panel.
	  * This function need not actually do something.
	*/
	public void saveData() {
	}

	/**
	  * This function is called to define the components which are a part of this
	  * panel.
	  * This function is called by the constructor to set up the normal static
	  * components and their locations.
	  * This method is required.
	*/
	protected void defineComponents() {
		try {
			Stock_Data selectedStock;
			StockOwnership_Data selectedOwnershipStock;

			this.setTitle("Stock Ownership Information");
			this.setBackground(Color.LIGHT_GRAY);
			btnOk.setBackground(Color.GRAY);

			lblMain.setFont(level1);

			// Add components to the panel, and specify x, y, width, height
			add(
				lblMain,
				new XYConstraints(this.FRAMEWIDTH / 2 - 150, 25, 400, 20));
			add(lblStockName, new XYConstraints(50, 75, 400, 20));
			add(lblStockCode, new XYConstraints(50, 100, 400, 20));
			add(lblHigh, new XYConstraints(50, 125, 400, 20));
			add(lblLow, new XYConstraints(50, 150, 400, 20));
			add(lblTotalQty, new XYConstraints(50, 225, 400, 20));
			add(lblTotalCost, new XYConstraints(50, 200, 400, 20));
			add(lblAvgCost, new XYConstraints(50, 250, 400, 20));
			add(lblLastPurchaseQty, new XYConstraints(50, 325, 400, 20));
			add(lblLastPurchaseAmount, new XYConstraints(50, 300, 400, 20));
			add(lblLastPurchaseRate, new XYConstraints(50, 350, 400, 20));
			add(lblDateLastPurchased, new XYConstraints(50, 375, 400, 20));
			add(
				btnOk,
				new XYConstraints(this.FRAMEWIDTH / 2 - 100, 410, 200, 20));
			lblMain.setText("Stock Ownership Information");

			btnOk.setLabel("OK");
			btnOk.addActionListener(this);

			addWindowListener(this);
			addActionListener(this);

			if (index == null || index.length() == 0)
				return;
			else {
				selectedStock = getStock(index);
				selectedOwnershipStock = getOwnershipStock(index);
			}

			lblStockName.setText(
				"Stock Name              : " + selectedStock.getCompanyName());
			lblStockCode.setText(
				"Stock Code               : " + selectedStock.getStockCode());
			lblHigh.setText(
				"52 week high            : $" + selectedStock.getWeekHigh());
			lblLow.setText(
				"52 week low              : $" + selectedStock.getWeekLow());
			lblTotalQty.setText(
				"Total Quantity owned        : "
					+ selectedOwnershipStock.getQuantityOwned());
			lblTotalCost.setText(
				"Total Purchase Cost         : $"
					+ selectedOwnershipStock.getTotalCost());
			lblAvgCost.setText(
				"Average Purchase Value  : $"
					+ calculateAverage(
						selectedOwnershipStock.getTotalCost(),
						selectedOwnershipStock.getQuantityOwned()));
			lblLastPurchaseQty.setText(
				"Quantity Last Purchased : "
					+ selectedOwnershipStock.getLastPurchaseQty());
			lblLastPurchaseAmount.setText(
				"Last Purchase Cost         : $"
					+ selectedOwnershipStock.getLastPurchaseAmount());
			lblLastPurchaseRate.setText(
				"Rate of Last Purchase     : $"
					+ calculateAverage(
						selectedOwnershipStock.getLastPurchaseAmount(),
						selectedOwnershipStock.getLastPurchaseQty()));
			lblDateLastPurchased.setText(
				"Last Purchase Date         : "
					+ selectedOwnershipStock
						.getLastPurchasedDate()
						.toLocaleString());

		} catch (ComponentHandlerException ex) {
			ex.printStackTrace();
		}
	}
	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		setVisible(false);
	}

	/**
	 * This method is being used for getting the parent application.
	 * @return StockTradingApplication The parent application.
	 */
	protected StockTradingApplication getStockTradingApplication() {
		return (StockTradingApplication) getParentApplication();
	}
	/**
	* This utility method is being used for calculating the average cost of shares.
	* @param cost The total amount spent on shares.
	* @param q The number of shares bought.
	* @return String The average cost of each share.
	*/
	private String calculateAverage(String cost, String q) {
		double result = 0;
		double total = Double.valueOf(cost).doubleValue();
		double qty = Double.valueOf(q).doubleValue();
		result = total / qty;
		result = round(result, 2);
		return String.valueOf(result);
	}
	
	/**
	 * This utility method is being used for rounding a given double to a specified
	 * number of decimal places.
	 * @param x The orginal double to be rounded.
	 * @param dec The number of decimal places to be rounded to.
	 * @return double The rounded double.
	 */
	public double round(double x, int dec) {
		double multiple = Math.pow(10, dec);
		return Math.round(x * multiple) / multiple;
	}
	
	/**
	 * Method: getStock
	 * This utility method is being used for getting stock details specified by
	 * the stock name.
	 * @param name The name of the stock details are to be retrived for.
	 * @return Stock_Data The stock details.
	 */
	private Stock_Data getStock(String name) {
		Stock_Data result = null;
		int count = 0;
		for (int g = 0; g < totalstocks.length; g++) {
			Stock_Data temp = (Stock_Data) totalstocks[g];
			if (name.equals(temp.toString())) {
				result = temp;
				count++;
				break;
			}
		}
		return result;
	}
	
	/**
	 * This utility method is being used for retrieving stock ownership details.
	 * @param name The name of stock ownership for which the details are to be 
	 * retrieved.
	 * @return StockOwnership_Data The stock ownership details.
	 */
	private StockOwnership_Data getOwnershipStock(String name) {
		StockOwnership_Data result = null;
		int count = 0;
		for (int g = 0; g < owned.length; g++) {
			StockOwnership_Data temp = (StockOwnership_Data) owned[g];
			if (name.equals(temp.toString())) {
				result = temp;
				count++;
				break;
			}
		}
		return result;
	}

	/* (non-Javadoc)
	 * @see amber.awt.event.ComponentWindowListener#windowOpened(amber.awt.event.ComponentWindowEvent)
	 */
	public void windowOpened(ComponentWindowEvent arg0) {
	}
	/* (non-Javadoc)
	 * @see amber.awt.event.ComponentWindowListener#windowClosing(amber.awt.event.ComponentWindowEvent)
	 */
	public void windowClosing(ComponentWindowEvent arg0) {
		setVisible(false);
	}
	/* (non-Javadoc)
	 * @see amber.awt.event.ComponentWindowListener#windowClosed(amber.awt.event.ComponentWindowEvent)
	 */
	public void windowClosed(ComponentWindowEvent arg0) {
	}
	/* (non-Javadoc)
	 * @see amber.awt.event.ComponentWindowListener#windowIconified(amber.awt.event.ComponentWindowEvent)
	 */
	public void windowIconified(ComponentWindowEvent arg0) {
	}
	/* (non-Javadoc)
	 * @see amber.awt.event.ComponentWindowListener#windowDeiconified(amber.awt.event.ComponentWindowEvent)
	 */
	public void windowDeiconified(ComponentWindowEvent arg0) {
	}
	/* (non-Javadoc)
	 * @see amber.awt.event.ComponentWindowListener#windowActivated(amber.awt.event.ComponentWindowEvent)
	 */
	public void windowActivated(ComponentWindowEvent arg0) {
	}
	/* (non-Javadoc)
	 * @see amber.awt.event.ComponentWindowListener#windowDeactivated(amber.awt.event.ComponentWindowEvent)
	 */
	public void windowDeactivated(ComponentWindowEvent arg0) {
	}
}