/**
 * 
 */
package test;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Locale;
import java.util.Random;

import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSeparator;
import javax.swing.JTextField;


/**
 * @author Arturas Gusevas
 *
 */
public class UtilityPanel {
	
	private JRadioButton demoRadioButton;
	private JRadioButton test2RadioButton;
	private JRadioButton test1RadioButton;
	private ButtonGroup buttonGroup = new ButtonGroup();
	public final static int  RIBA = 10;
	
	public final static double  ZINGSNIS = 1.0 / RIBA ; 

	private JPanel panel = new JPanel(); //pagrindine panel
	
	JButton runTestButton, drawButton;

	public JComboBox functionComboBox;

	JTextField wVTextField[] = new JTextField[9], resourceTextField;

	JPanel wWestPanel, wEastPanel, wSouthPanel, wFlowPanel;

	// piesia grafika
	MeGraphicsf wGraphics;

	// Naudingumo funkcijos reiksmes
	public double Uf[] = new double[RIBA+1];

	//resursas
	public int resource = 100, 
		fc = 0;

	double naud_f[][] = {{0.0,    0.0,	  0.0,   0.0},
             			 {0.5,    0.02,   0.1,   0.02},
             			 {0.675,  0.05,   0.2,   0.045},
             			 {0.75,   0.0745, 0.3,   0.1},
             			 {0.8,    0.115,  0.4,   0.2},
             			 {0.845,  0.155,  0.5,   0.5},
             			 {0.885,  0.2, 	  0.6,   0.8},
             			 {0.9255, 0.25,   0.7,   0.9},
             			 {0.95,   0.325,  0.8,   0.955}, 
             			 {0.98,   0.5,    0.9,   0.98},
             			 {1.0,    1.0,    1.0,   1.0},};
	
	/**
	 * 
	 */
	public UtilityPanel() {
		init();
	}
	
	

	// ------ ItemListener ----------------------------------------
	class CItemListener implements ItemListener {
		public void itemStateChanged(ItemEvent e) {
			fc = fc + 1;
			if (fc == 3)
				fc = 1;
			if (fc == 1) {
				String Str = "" + ((JComboBox) e.getSource()).getSelectedItem();
				if (((JComboBox) e.getSource()).getName() == "IType") {
					int Risk = 2;
					if (Str.equals("Rich"))
						Risk = 2;
					if (Str.equals("Real"))
						Risk = 3;
					if (Str.equals("Prudent"))
						Risk = 0;
					if (Str.equals("Risky"))
						Risk = 1;
					/*if (Str.equals("User")) {
						Risk = 2;
						((JComboBox) e.getSource()).setSelectedIndex(2);
					}*/
						
					for (int i = 0; i < RIBA-1; i++) {
						wVTextField[i].setText("" + naud_f[i + 1][Risk]);
					}
					CheckValues();
				}
			}
		}
	}

	CItemListener wItemListener = new CItemListener();

	// ------ FocusListener Integer Double ----------------------------
	class CLFocusListener extends FocusAdapter {
		public void focusLost(FocusEvent e) {
			String Str = ((JTextField) e.getSource()).getText();
			//if function value
			if (((JTextField) e.getSource()).getName() == "Double") {
				if (Str.length() == 0) {
					((JTextField) e.getSource()).setText("0.1");
					((JTextField) e.getSource()).setBackground(new Color(255,
							255, 255));
				} else
					try {
						double d = Double.parseDouble(Str);
						if (d < 0.0)
							d = d * -1;
						if (d > 1)
							d = 1;
						((JTextField) e.getSource())
								.setText(Double.toString(d));
						//getAppletContext().showStatus("");
						((JTextField) e.getSource()).setBackground(new Color(
								255, 255, 255));
					} catch (NumberFormatException exc) {
						//getAppletContext().showStatus("Error: It's not floating point value!");
						((JTextField) e.getSource()).setBackground(new Color(
								255, 90, 90));
					}
			}
			//if resource value
			if (((JTextField) e.getSource()).getName() == "Integer") {
				if (Str.length() == 0) {
					((JTextField) e.getSource()).setText("1");
					((JTextField) e.getSource()).setBackground(new Color(255,
							255, 255));
				} else
					try {
						int n = Integer.parseInt(Str);
						if (n < 0.0)
							n = n * -1;
						if (n < 100)
							n = 100;
						if (n > 1000000)
							n = 1000000;
						((JTextField) e.getSource()).setText(Integer
								.toString(n));
						//getAppletContext().showStatus(" ");
						((JTextField) e.getSource()).setBackground(new Color(
								255, 255, 255));
						runTestButton.setEnabled(true);
						resource = n;
					} catch (NumberFormatException exc) {
						//getAppletContext().showStatus("Error: It's not number value or to large!");
						runTestButton.setEnabled(false);
						((JTextField) e.getSource()).setBackground(new Color(
								255, 90, 90));
					}
			}
			System.out.println("Pasikeite resursas: " + resource);
		}
	}

	CLFocusListener wTLFocusListener = new CLFocusListener();

	
	// ------ ActionListener ----------------------------------------
	//------- Clicked "Draw" or "Run Test" Button -------------------
	//---------------------------------------------------------------
	class CActionListener implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			Object wObject = e.getSource();
			if (wObject == drawButton) {
				CheckValues();
			}
			if (wObject == runTestButton) {
				if (test1RadioButton.isSelected() == true) {
					double tmp[] = new double[UtilityPanel.RIBA+1];
					for (int i = 0; i < UtilityPanel.RIBA+1; i++)
						tmp[i] = 0.0;
					functionComboBox.setSelectedIndex(4);
					Test wTest = new Test(null, resource);
					tmp = wTest.Run1();
					if (tmp[0] != -1) {
						for (int i = 0; i < UtilityPanel.RIBA-1; i++) {
							wVTextField[i].setText("" + tmp[i + 1]);
						}
						CheckValues();
					}
				} else if (test2RadioButton.isSelected() == true) {
					double tmp[] = new double[UtilityPanel.RIBA+1];
					for (int i = 0; i < UtilityPanel.RIBA+1; i++)
						tmp[i] = 0.0;
					functionComboBox.setSelectedIndex(4);
					Test wTest = new Test(null, resource);
					tmp = wTest.Run2();
					if (tmp[0] != -1) {
						for (int i = 0; i < UtilityPanel.RIBA-1; i++) {
							wVTextField[i].setText("" + tmp[i + 1]);
						}
						CheckValues();
					}
				} else if (demoRadioButton.isSelected() == true) {
					Random random = new Random();
					double [] masyvas = new double[UtilityPanel.RIBA];
					
					for (int i = 0; i < UtilityPanel.RIBA; i++) {
						masyvas[i] = random.nextDouble();
					}
					Arrays.sort(masyvas);
					
					for (int i = 0; i < UtilityPanel.RIBA-1; i++) {
						wVTextField[i].setText("" + masyvas[i + 1]);
					}
					CheckValues();
				}
			}
		}
	}

	CActionListener wBActionListener = new CActionListener();

	/**
	 * Checks if all values are correct
	 *
	 */
	void CheckValues() {
		for (int i = 0; i < RIBA-1; i++) {
			try {
				//double d = 
					Double.parseDouble(wVTextField[i].getText());
				//getAppletContext().showStatus("");
				wVTextField[i].setBackground(new Color(255, 255, 255));
			} catch (NumberFormatException exc) {
				//getAppletContext().showStatus("Error: It's not floating point value!");
				wVTextField[i].setBackground(new Color(255, 90, 90));
				return;
			}
		}
		for (int i = 0; i < RIBA-2; i++) {
			double d = Double.parseDouble(wVTextField[i].getText());
			double dd = Double.parseDouble(wVTextField[i + 1].getText());
			if (d > dd) {
				/*getAppletContext().showStatus(
						"Error: " + (i + 1)
								+ " value must be less or equal then "
								+ (i + 2) + " value!");*/
				wVTextField[i].setBackground(new Color(255, 90, 90));
				wVTextField[i + 1].setBackground(new Color(255, 90, 90));
				return;
			}
		}
		WriteUf();
	}

	/**
	 * 
	 * 
	 */
	void WriteUf() {
		Uf[0] = 0.0;
		Uf[RIBA] = 1.0;
		for (int i = 0; i < RIBA-1; i++) {
			double d = Double.parseDouble(wVTextField[i].getText());
			Uf[i + 1] = d;
		}
		wGraphics.Data(Uf);
		wGraphics.repaint();
	}

	// **************************************************************/
	// **************************************************************/

	public void init() {
		
		panel.setLayout(new BorderLayout());
		// --------------------------------------------------------------

		int Width = 150, Height = 28;
		Color Background = new Color(161, 161, 161), Foreground = new Color(66,
				75, 145);

		// -------- Add to wEasthPanel ----------------
		wEastPanel = new JPanel();
		wEastPanel.setLayout(new BoxLayout(wEastPanel, BoxLayout.Y_AXIS));
		wFlowPanel = new JPanel();
		wFlowPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
		JLabel wLabel = new JLabel("  Function value ");
		wLabel.setPreferredSize(new Dimension(Width + 15, Height));
		wLabel.setOpaque(true);
		wLabel.setBackground(Background);
		wLabel.setForeground(Foreground);
		wFlowPanel.add(wLabel);
		wEastPanel.add(wFlowPanel);

		wFlowPanel = new JPanel();
		wFlowPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		wLabel = new JLabel("R.");
		wLabel.setToolTipText("Resources");
		wFlowPanel.add(wLabel);
		resourceTextField = new JTextField("100");
		resourceTextField.setPreferredSize(new Dimension(Width, Height));
		resourceTextField.setToolTipText("Resources Min = 100; Max = 1000000");
		resourceTextField.setName("Integer");
		resourceTextField.addFocusListener(wTLFocusListener);
		wFlowPanel.add(resourceTextField);
		wEastPanel.add(wFlowPanel);

		//Function: Rich, Real, Prudent, Risky
		wFlowPanel = new JPanel();
		wFlowPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		wLabel = new JLabel("F.");
		wLabel.setToolTipText("Functions");
		wFlowPanel.add(wLabel);
		functionComboBox = new JComboBox();
		functionComboBox.addItem("Rich");
		functionComboBox.addItem("Real");
		functionComboBox.addItem("Prudent");
		functionComboBox.addItem("Risky");
		functionComboBox.addItem("User");
		functionComboBox.setPreferredSize(new Dimension(Width, Height));
		functionComboBox.setToolTipText("Functions");
		functionComboBox.addItemListener(wItemListener);
		functionComboBox.setName("IType");
		wFlowPanel.add(functionComboBox);
		wEastPanel.add(wFlowPanel);

		Locale locale = Locale.CANADA;
		String number = "";
		
		Uf[0] = 0.0;
		Uf[RIBA] = 1.0;
		for (int i = 0; i < RIBA-1; i++) {
			wFlowPanel = new JPanel();
			wFlowPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
			wLabel = new JLabel("" + (i + 1) + ".");
			wFlowPanel.add(wLabel);
			
			number = NumberFormat.getNumberInstance(locale).format((i + 1) * ZINGSNIS);
			wVTextField[i] = new JTextField("" + (Double.parseDouble(number)));			
			
			Uf[i + 1] = Double.parseDouble(number);
			
			wVTextField[i].setPreferredSize(new Dimension(Width, Height));
			wVTextField[i].setToolTipText("Min = 0; Max = 1");
			wVTextField[i].setName("Double");
			wVTextField[i].addFocusListener(wTLFocusListener);
			wFlowPanel.add(wVTextField[i]);
			wEastPanel.add(wFlowPanel);
		}
		wFlowPanel = new JPanel();
		wFlowPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
		drawButton = new JButton("Draw");
		drawButton.addActionListener(wBActionListener);
		drawButton.setPreferredSize(new Dimension(Width, Height));
		wFlowPanel.add(drawButton);
		wEastPanel.add(wFlowPanel);

		// -------- Add to wWestPanel ----------------

		wWestPanel = new JPanel();
		wWestPanel.setLayout(new BorderLayout());
		wFlowPanel = new JPanel();
		FlowLayout FlowL = new FlowLayout(FlowLayout.LEFT);
		FlowL.setVgap(3);
		wFlowPanel.setLayout(FlowL);
		wWestPanel.add(wFlowPanel, BorderLayout.NORTH);
		wFlowPanel = new JPanel();
		FlowL = new FlowLayout(FlowLayout.LEFT);
		FlowL.setHgap(3);
		wWestPanel.add(wFlowPanel, BorderLayout.WEST);
		wFlowPanel.setLayout(FlowL);

		wGraphics = new MeGraphicsf(Uf);
		wWestPanel.add(wGraphics, BorderLayout.CENTER);

		// -------- Add to wSouthPanel ---------------

		wSouthPanel = new JPanel();
		wSouthPanel.setLayout(new BorderLayout());

		wFlowPanel = new JPanel();
		wFlowPanel.setLayout(new BorderLayout());
		wSouthPanel.add(wFlowPanel, BorderLayout.NORTH);

		final JSeparator separator = new JSeparator();
		separator.setPreferredSize(new Dimension(100, 5));
		wFlowPanel.add(separator);
		wFlowPanel = new JPanel();
		FlowL = new FlowLayout();
		FlowL.setVgap(3);
		wFlowPanel.setLayout(FlowL);
		wSouthPanel.add(wFlowPanel, BorderLayout.SOUTH);
		wFlowPanel = new JPanel();
		FlowL = new FlowLayout();
		FlowL.setHgap(3);
		wFlowPanel.setLayout(FlowL);
		wSouthPanel.add(wFlowPanel, BorderLayout.WEST);
		wFlowPanel = new JPanel();
		FlowL = new FlowLayout();
		FlowL.setHgap(2);
		wFlowPanel.setLayout(FlowL);
		wSouthPanel.add(wFlowPanel, BorderLayout.EAST);

		JPanel West = new JPanel();
		West.setLayout(new BorderLayout());


		runTestButton = new JButton("Run test");
		runTestButton.addActionListener(wBActionListener);
		West.add(runTestButton, BorderLayout.EAST);
		

		wSouthPanel.add(West);

		final JPanel panel_1 = new JPanel();
		West.add(panel_1, BorderLayout.CENTER);

		test1RadioButton = new JRadioButton();
		buttonGroup.add(test1RadioButton);
		test1RadioButton.setSelected(true);
		test1RadioButton.setText("Test1");
		//panel_1.add(test1RadioButton);
		

		test2RadioButton = new JRadioButton();
		buttonGroup.add(test2RadioButton);
		test2RadioButton.setText("Test2");
		test2RadioButton.setSelected(true);
		panel_1.add(test2RadioButton);

		demoRadioButton = new JRadioButton();
		buttonGroup.add(demoRadioButton);
		demoRadioButton.setText("Demo");
		panel_1.add(demoRadioButton);

		// -------- Add to applet ---------------------
		panel.add(wWestPanel);
		panel.add(wEastPanel, "East");
		panel.add(wSouthPanel, "South");
		// --------------------------------------------------------------
		
		System.out.println("Finished");
	} // End Init

	/**
	 * 
	 * @return Returns UtilityF panel
	 */
	public JPanel getPanel() {
		return panel;
	}
	
	public JTextField[] getPanelTextFields() {
		return wVTextField;
	}

}
