/**
 *	JFractionLab
 *	Copyright (C) 2005 jochen georges, gnugeo _ at _ gnugeo _ dot _ de
 *
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU General Public License for more details.
 *
 *	You should have received a copy of the GNU General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 **/

package jfractionlab.exerciseDialogs;

import info.clearthought.layout.TableLayout;

import java.awt.Color;
import java.awt.Container;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JLabel;

import jfractionlab.FractionMaker;
import jfractionlab.HelpStarter;
import jfractionlab.JFractionLab;
import jfractionlab.MyJTextField;
import jfractionlab.displays.FractionAsRectangle;
import jfractionlab.displays.FractionLine;
import jfractionlab.exerciseGenerator.ExerciseGenerator;
import jfractionlab.jflDialogs.UsabilityDialog;
import jfractionlab.jflDialogs.WorkSheetDialog;





public class DivideFractionsByNumbers extends ExerciseDialog implements ActionListener, KeyListener{
	static final long serialVersionUID = JFractionLab.serialVersionUID;
		//GUI

		private MyJTextField tf_numerator1 = new MyJTextField(2);
		private MyJTextField tf_calculation_numerator1 = new MyJTextField(2);
		private MyJTextField tf_calculation_numerator2 = new MyJTextField(2);
		private MyJTextField tf_reduced_numerator1 = new MyJTextField(2);
		private MyJTextField tf_endresult_numerator = new MyJTextField(2);

		private MyJTextField tf_denominator1 = new MyJTextField(2);
		private MyJTextField tf_calculation_denominator1 = new MyJTextField(2);
		private MyJTextField tf_calculation_denominator2 = new MyJTextField(2);
		private MyJTextField tf_reduced_denominator1 = new MyJTextField(2);
		private MyJTextField tf_reduced_denominator2 = new MyJTextField(2);
		private MyJTextField tf_endresult_denominator = new MyJTextField(2);

		private MyJTextField tf_divisor =  new MyJTextField(2);
		private JLabel lb_divisor =  new JLabel("", JLabel.CENTER);
		//"MetaTextFields"
		//bietet Zugang zu dem "inneren", im Krzungsprozess aktuellem Textfeld
		private MyJTextField tf_reduce_inner_numerator;
		private MyJTextField tf_reduce_inner_denominator;
		//bietet Zugang zu dem "��ren", im Krzungsprozess aktuellem Textfeld
		private MyJTextField tf_reduce_outer_numerator;
		private MyJTextField tf_reduce_outer_denominator;
		
		private FractionAsRectangle pizza = new FractionAsRectangle();
		private FractionAsRectangle calculation_pizza = new FractionAsRectangle();
		private FractionAsRectangle endresult_pizza = new FractionAsRectangle();

		//Zahlen
		//private EchterBruch fraction1;
		private FractionMaker fraction1 = new FractionMaker();
		private int numerator1;
		private int denominator1;
		private int divisor;

		/**
		 * 
		 * @param owner
		 * @param lx
		 * @param ly
		 * @param sx
		 * @param sy
		 * @throws HeadlessException
		 */
		public DivideFractionsByNumbers(JFractionLab owner, int lx, int ly, int sx, int sy) throws HeadlessException {
			super(lx, ly, sx, sy);
			setTitle(lang.Messages.getString("divide_the_frac"));
			btn_continue = new JButton(lang.Messages.getString("continue"));
			btn_end =  new JButton(lang.Messages.getString("end"));
			this.owner = owner;
			
			//Menu
			rb_random.addActionListener(this);
			jmOptions.add(rb_random);
			rb_custom.addActionListener(this);
			jmOptions.add(rb_custom);
			
			jmb.add(jmOptions);
			
			jmiCreateWorkSheet.addActionListener(this);
			jmWorkSheet.add(jmiCreateWorkSheet);
			jmb.add(jmWorkSheet);

			jmiHelp.addActionListener(this);
			jmb.add(jmHelp);
			setJMenuBar(jmb);
			
			double sizes[][] = {{
				// Spalten
				0.1,0.05,0.025,
				0.05,0.1,0.025,
				0.0885,0.05,0.05,
				0.05,0.0885,0.025,
				0.05,0.05,0.05,
				0.14,0.01
			},{
				//Zeilen
				TableLayout.FILL,
				TableLayout.FILL,
				12,
				TableLayout.FILL,
				TableLayout.FILL,
				0.60,
				30
			}};

			Container content = getContentPane();
	        	content.setLayout(new TableLayout(sizes));
			content.setBackground(Color.white);
			//--Zaehler
				addTextField(tf_numerator1);
				tf_numerator1.addKeyListener(this);
				tf_numerator1.setEditable(false);
			content.add(tf_numerator1, "1,1,c,b");
				addTextField(tf_divisor);
				tf_divisor.addKeyListener(this);
				tf_divisor.setEditable(false);
			content.add(tf_divisor, "3,1,3,3,c,c");
				addTextField(tf_calculation_numerator1);
				tf_calculation_numerator1.setEditable(false);
			content.add(tf_calculation_numerator1, "7,1,r,b");
				addTextField(tf_calculation_numerator2);
				tf_calculation_numerator2.setEditable(false);
				tf_calculation_numerator2.addKeyListener(this);
			content.add(tf_calculation_numerator2, "9,1,l,b");
				addTextField(tf_reduced_numerator1);
				tf_reduced_numerator1.addKeyListener(this);
				tf_reduced_numerator1.setEditable(false);
			content.add(tf_reduced_numerator1, "7,0,r,b");
				addTextField(tf_endresult_numerator);
				tf_endresult_numerator.addKeyListener(this);
				tf_endresult_numerator.setEditable(false);
			content.add(tf_endresult_numerator, "13,1,c,b");
			//--Nenner
				addTextField(tf_denominator1);
				tf_denominator1.addKeyListener(this);
				tf_denominator1.setEditable(false);
			content.add(tf_denominator1, "1,3,c,t");
				addTextField(tf_calculation_denominator1);
				tf_calculation_denominator1.setEditable(false);
			content.add(tf_calculation_denominator1, "7,3,r,t");
				addTextField(tf_calculation_denominator2);
				tf_calculation_denominator2.addKeyListener(this);
				tf_calculation_denominator2.setEditable(false);
			content.add(tf_calculation_denominator2, "9,3,l,t");
				addTextField(tf_reduced_denominator1);
				tf_reduced_denominator1.addKeyListener(this);
				tf_reduced_denominator1.setEditable(false);
			content.add(tf_reduced_denominator1, "7,4,r,t");
				addTextField(tf_reduced_denominator2);
				tf_reduced_denominator2.addKeyListener(this);
				tf_reduced_denominator2.setEditable(false);
			content.add(tf_reduced_denominator2, "9,4,l,t");
				addTextField(tf_endresult_denominator);
				tf_endresult_denominator.addKeyListener(this);
				tf_endresult_denominator.setEditable(false);
			content.add(tf_endresult_denominator, "13,3,c,t");

			//--Zeichen
			JLabel lb_geteiltzeichen = new JLabel(":", JLabel.CENTER);
			content.add(lb_geteiltzeichen, "2,2");
			JLabel lb_geteiltzeichen2 = new JLabel(":", JLabel.CENTER);
			content.add(lb_geteiltzeichen2, "2,5");
			content.add(lb_divisor, "3,5");
			JLabel lb_calculationsMal1 = new JLabel("*", JLabel.CENTER);
			content.add(lb_calculationsMal1, "8,1,c,b");
			JLabel lb_calculationsMal2 = new JLabel("*", JLabel.CENTER);
			content.add(lb_calculationsMal2, "8,3,c,t");
			JLabel lb_gleich1 = new JLabel("=", JLabel.CENTER);
			content.add(lb_gleich1, "5,2");
			JLabel lb_gleich1u = new JLabel("=", JLabel.CENTER);
			content.add(lb_gleich1u, "5,5");
			JLabel lb_gleich2 = new JLabel("=", JLabel.CENTER);
			content.add(lb_gleich2, "11,2");
			JLabel lb_gleich2u = new JLabel("=", JLabel.CENTER);
			content.add(lb_gleich2u, "11,5");
			
			FractionLine bs_fraction1 = new FractionLine();
			content.add(bs_fraction1, "1,2");
			FractionLine bs_fraction3 = new FractionLine();
			content.add(bs_fraction3, "7,2,9,2");
			FractionLine bs_fraction4 = new FractionLine();
	        	content.add(bs_fraction4, "13,2");
			//--Pizzen
			content.add(pizza, "0,5,1,5");
			content.add(calculation_pizza, "7,5,9,5");
			content.add(endresult_pizza, "12,5,14,5");

			btn_continue.addActionListener(this);
			btn_continue.addKeyListener(this);
			btn_continue.setFocusTraversalKeysEnabled(false);
			content.add(btn_continue, "15,1,c,b");
			btn_end.addActionListener(this);
			btn_end.addKeyListener(this);
			content.add(btn_end, "15,3,c,b");
			content.add(pdsp, "15,4,15,5");
			points = owner.points_divideFractionsByNumbers;
			pdsp.setText(String.valueOf(points));
			lb_info.setFont(JFractionLab.infofont);
			lb_info.setText(lang.Messages.getString("you_just_need_nb_and_enter"));
			content.add(lb_info, "0,6,15,6");
			
			makeProblem();
			String[] ar_howto = {
				"howto_nb_and_enter","howto_option_type_of_exercise"
			};
			new UsabilityDialog(ar_howto);//new UsabilityDialog
		}//Konstruktor
		
		/**
		 * 
		 *
		 */
		protected void makeProblem(){
			//System.out.println("makeProblem");
			fraction1.mkOneFraction(9);
			numerator1 = fraction1.getNumerator_1();
			denominator1 = fraction1.getDenominator_1();
			try {
				Thread.sleep(1);
			}catch (InterruptedException e) {e.printStackTrace();}
			divisor = (Math.abs(JFractionLab.ran.nextInt())%8)+2;//+2 verhindert 0 und 1
			//System.out.println("makeProblem(): "+numerator1+"/"+denominator1+", "+divisor);
			//numerator1 = 18;
			//denominator1 = 24;
			//divisor = 9;
			//erster Bruch
			tf_numerator1.setText(String.valueOf(numerator1));
			tf_denominator1.setText(String.valueOf(denominator1));
			pizza.drawPizzaAsRectangle(numerator1, denominator1, Color.yellow, false,true);
			// ganzzahliger Divisor
			tf_divisor.setText(String.valueOf(divisor));
			lb_divisor.setText(String.valueOf(divisor));
			//Rechnung:
			tf_calculation_numerator1.setText(String.valueOf(numerator1));
			tf_calculation_denominator1.setText(String.valueOf(denominator1));
			tf_calculation_numerator2.setEditable(true);
			tf_calculation_numerator2.requestFocusInWindow();
			
		}//makeProblem
		
		/**
		 * 
		 *
		 */
	 	private void checkReducability(){
			if(JFractionLab.greatestCommonDivisor(Integer.parseInt(tf_calculation_numerator1.getText()),Integer.parseInt(tf_calculation_denominator1.getText())) != 1){
				initReductionProcess(1,1);
			}else if(JFractionLab.greatestCommonDivisor(Integer.parseInt(tf_calculation_numerator1.getText()),Integer.parseInt(tf_calculation_denominator2.getText())) != 1){
				initReductionProcess(1,2);
			}else if(JFractionLab.greatestCommonDivisor(Integer.parseInt(tf_calculation_numerator2.getText()),Integer.parseInt(tf_calculation_denominator1.getText())) != 1){
				initReductionProcess(2,1);
			}else if(JFractionLab.greatestCommonDivisor(Integer.parseInt(tf_calculation_numerator2.getText()),Integer.parseInt(tf_calculation_denominator2.getText())) != 1){
				initReductionProcess(2,2);
			}else{
				tf_endresult_numerator.setEditable(true);
				tf_endresult_numerator.requestFocusInWindow();
				//tf_endresult_numerator.requestFocusInWindow();
			}
		}//public void checkReducability()

	 	/**
	 	 * 
	 	 * @param z
	 	 * @param n
	 	 */
		private void initReductionProcess(int z, int n){
			//System.out.println("initReductionProcess("+ z+","+n+")");
			tf_reduce_inner_numerator = tf_calculation_numerator1;
			tf_reduce_outer_numerator = tf_reduced_numerator1;
			if (n == 1){
				tf_reduce_inner_denominator = tf_calculation_denominator1;
				tf_reduce_outer_denominator = tf_reduced_denominator1;
			}else if(n == 2){
				tf_reduce_inner_denominator = tf_calculation_denominator2;
				tf_reduce_outer_denominator = tf_reduced_denominator2;
			}else{
				//???
			}
			tf_reduce_outer_denominator.setEditable(true);
			tf_reduce_outer_numerator.setEditable(true);
			tf_reduce_outer_numerator.requestFocusInWindow();
		}//initReductionProcess

		/**
		 * 
		 *
		 */
		protected void nextProblem(){
			clearTextFields();
			lb_divisor.setText("");
			pizza.noPizzaAsRectangle();
			calculation_pizza.noPizzaAsRectangle();
			endresult_pizza.noPizzaAsRectangle();
			if (bl_randomProblem == true){
				makeProblem();
			}else{
				tf_numerator1.setText("");
				tf_numerator1.setEditable(true);
				tf_numerator1.requestFocusInWindow();
			}
		}//public void nextProblem()

		/**
		 * 
		 */
		public void actionPerformed (ActionEvent e) {
			Object obj = e.getSource();
			if (obj == btn_continue){
				nextProblem();
			}else if (obj == btn_end){
				close_it();
			}else if (obj == rb_random){
				//System.out.println("rb_random");
				//the program is in "custom-mode" actually
				//it should switch to "random-mode"
				bl_randomProblem = true;
				nextProblem();
			}else if (obj == rb_custom){
				//System.out.println("rb_custom");
				//the program is in "random-mode" actually
				//it should switch to "custom-mode"
				bl_randomProblem = false;
				nextProblem();
			}else if(obj == jmiCreateWorkSheet){
				new WorkSheetDialog(
						ExerciseGenerator.DIVIDE_FRACTIONS,
						lang.Messages.getString("div_fr_by_fr"),
						lang.Messages.getString("fractions")
				);
			}else if(obj == jmiHelp){
				new HelpStarter(
						lang.Messages.getLocale().toString(),
						"divide-by-numbers"
				);
			}
		}//actionPerformed

		/**
		 * 
		 */
		public void keyPressed(KeyEvent event){
			Object obj = event.getSource();
			int key = event.getKeyCode();
			lb_info.setText("");
			if(obj == tf_numerator1 & key == KeyEvent.VK_ENTER){
				if(readInputInt(tf_numerator1)!=null){
					numerator1 = Integer.parseInt(tf_numerator1.getText());
					tf_numerator1.setEditable(false);
					tf_denominator1.setEditable(true);
					tf_denominator1.requestFocusInWindow();
				}
			}else if(obj == tf_denominator1 & key == KeyEvent.VK_ENTER){
				if(readInputInt(tf_denominator1)!=null){
					int pn = Integer.parseInt(tf_denominator1.getText());
					if(pn <= numerator1){
						lb_info.setText(lang.Messages.getString("dn_must_be_bigger"));
						tf_denominator1.setText("");
						tf_denominator1.setEditable(false);
						tf_numerator1.setText("");
						tf_numerator1.setEditable(true);
						tf_numerator1.requestFocusInWindow();
					}else{
						denominator1 = pn;
						tf_denominator1.setEditable(false);
						pizza.drawPizzaAsRectangle(numerator1, denominator1, Color.yellow, false,true);
						tf_divisor.setEditable(true);
						tf_divisor.requestFocusInWindow();
					}
				}
			}else if(obj == tf_divisor & key == KeyEvent.VK_ENTER){
				if(readInputInt(tf_divisor)!=null){
					divisor = Integer.parseInt(tf_divisor.getText());
					lb_divisor.setText(String.valueOf(divisor));
					tf_calculation_numerator1.setText(String.valueOf(numerator1));
					tf_calculation_denominator1.setText(String.valueOf(denominator1));
					tf_divisor.setEditable(false);
					tf_calculation_numerator2.setEditable(true);
					tf_calculation_numerator2.requestFocusInWindow();
				}
			}else if(obj == tf_calculation_numerator2 & key == KeyEvent.VK_ENTER){
				//System.out.println("tf_calculation_numerator2");
				if(readInputInt(tf_calculation_numerator2)!=null){
					int z = Integer.parseInt(tf_calculation_numerator2.getText());
					if(z!= 1){
						lb_info.setText(lang.Messages.getString("mk_reciprocal"));
						tf_calculation_numerator2.setText("");
					}else{
						tf_calculation_numerator2.setEditable(false);
						tf_calculation_denominator2.requestFocusInWindow();
						tf_calculation_denominator2.setEditable(true);
					}
				}
			}else if(obj == tf_calculation_denominator2 & key == KeyEvent.VK_ENTER){
				//System.out.println("tf_calculation_denominator2");
				if(readInputInt(tf_calculation_denominator2)!=null){
					int z = Integer.parseInt(tf_calculation_denominator2.getText());
					if( z != Integer.parseInt(tf_divisor.getText()) ){
						//System.out.println("Nenner : falsche Zahl");
						lb_info.setText(lang.Messages.getString("mk_reciprocal"));
						tf_calculation_denominator2.setText("");
					}else{
						tf_calculation_denominator2.setEditable(false);
						calculation_pizza.drawPizzaAsRectangle(
							numerator1, denominator1, 1, z, Color.yellow,true
						);
						checkReducability();
					}
				}
			}else if(obj == tf_reduced_numerator1 & key == KeyEvent.VK_ENTER){
				if(readInputInt(tf_reduced_numerator1)!=null){
					tf_reduce_outer_numerator_Action();
				}
			}else if(obj == tf_reduced_denominator1 & key == KeyEvent.VK_ENTER){
				if(readInputInt(tf_reduced_denominator1)!=null){
					tf_reduce_outer_denominator_Action();
				}
			}else if(obj == tf_reduced_denominator2 & key == KeyEvent.VK_ENTER){
				if(readInputInt(tf_reduced_denominator2)!=null){
					tf_reduce_outer_denominator_Action();
				}
			}else if(obj == tf_endresult_numerator & key == KeyEvent.VK_ENTER){
				if(readInputInt(tf_endresult_numerator)!=null){
					int z1 = Integer.parseInt(tf_calculation_numerator1.getText());
					int z2 = Integer.parseInt(tf_calculation_numerator2.getText());
					int zz = Integer.parseInt(tf_endresult_numerator.getText());
					//System.out.println("focusLost obj == tf_endresult_numerator -- try");
					//System.out.println(z1+", "+z2+", "+zz);
					if(z1 * z2 != zz){
						lb_info.setText(lang.Messages.getString("multiply_nums"));
						tf_endresult_numerator.setText("");
					}else{
						tf_endresult_numerator.setEditable(false);
						tf_endresult_denominator.setEditable(true);
						tf_endresult_denominator.requestFocusInWindow();
					}
				}
			}else if(obj == tf_endresult_denominator & key == KeyEvent.VK_ENTER){
				if(readInputInt(tf_endresult_denominator)!=null){
					int cn1 = Integer.parseInt(tf_calculation_numerator1.getText());
					int cn2 = Integer.parseInt(tf_calculation_numerator2.getText());
					int cd1 = Integer.parseInt(tf_calculation_denominator1.getText());
					int cd2 = Integer.parseInt(tf_calculation_denominator2.getText());
					int ez  = Integer.parseInt(tf_endresult_numerator.getText());
					int en  = Integer.parseInt(tf_endresult_denominator.getText());
					if(cd1 * cd2 != en){
						lb_info.setText(lang.Messages.getString("multiply_denomis"));
						tf_endresult_denominator.setText("");
					}else{
						tf_endresult_denominator.setEditable(false);
						if(cn1 < cd1 && cn2 < cd2){
							endresult_pizza.drawPizzaAsRectangle(cn1, cd1, cn2, cd2, Color.yellow,true);
						}else{
							endresult_pizza.drawPizzaAsRectangle(ez, en, Color.yellow, false,true);
						}
						if(bl_randomProblem){points++;}
						pdsp.setText(String.valueOf(points));
						owner.setPoints(points, "divideFractionsByNumbers");
						lb_info.setText(lang.Messages.getString("that_is_right"));
						btn_continue.requestFocusInWindow();
					}
				}
			}else if(obj == btn_continue & key == KeyEvent.VK_ENTER){
				nextProblem();
			}else if(obj == btn_end & key == KeyEvent.VK_ENTER){
				close_it();
			}
		}//keyPressed
		public void keyTyped(KeyEvent event){}
		public void keyReleased(KeyEvent event){}

		/**
		 * 
		 *
		 */
		private void tf_reduce_outer_numerator_Action(){
			//System.out.println("tf_reduce_outer_numerator()");
			tf_reduce_outer_numerator.setEditable(false);
			tf_reduce_outer_denominator.setEditable(true);
			tf_reduce_outer_denominator.requestFocusInWindow();
		}
		
		/**
		 * 
		 *
		 */
		private void tf_reduce_outer_denominator_Action(){
			int z=0; int z_neu = 0; int n = 0; int n_neu = 0;
			boolean bol = true;
			try{
				z = Integer.parseInt(tf_reduce_inner_numerator.getText());
				z_neu = Integer.parseInt(tf_reduce_outer_numerator.getText());
				n = Integer.parseInt(tf_reduce_inner_denominator.getText());
				n_neu = Integer.parseInt(tf_reduce_outer_denominator.getText());
			}catch(NumberFormatException nfe){
				nfe.printStackTrace();
				lb_info.setText("error tf_reduce_outer_denominator_Action");
				bol = false;
			}
			if(bol){
				if(inRow(z,z_neu) && inRow(n,n_neu)){
					if(JFractionLab.greatestCommonDivisor(z_neu,n_neu) != 1 || z/z_neu != n/n_neu){ //Es kann weitergekrzt werden
						lb_info.setText(lang.Messages.getString("reduce_better"));
						tf_reduce_outer_numerator.setEditable(true);
						//tf_reduce_outer_denominator.setEditable(false);
						tf_reduce_outer_numerator.requestFocusInWindow();
					}else{//Es kann nicht weitergekrzt werden
						tf_reduce_outer_numerator.setEditable(false);
						tf_reduce_outer_denominator.setEditable(false);
						tf_reduce_outer_numerator.setText("");
						tf_reduce_outer_denominator.setText("");
						tf_reduce_inner_numerator.setText(String.valueOf(z_neu));
						tf_reduce_inner_denominator.setText(String.valueOf(n_neu));
						checkReducability();
					}//if (JFractionLab.ggt(z,n) != 1)
				}else{//sind nicht in Reihe
					//System.out.println("Eine der Zahlen ist keine Vielfache!!");
					lb_info.setText(lang.Messages.getString("div_n_and_dn_by_same_nb"));
					tf_reduce_outer_numerator.setEditable(true);
					tf_reduce_outer_denominator.setEditable(false);
					tf_reduce_outer_numerator.requestFocusInWindow();
					//tf_reduce_outer_numerator.setText("");
					//tf_reduce_outer_denominator.setText("");
				}//if in reihe
			}
		}
		
		/**
		 * 
		 * @param n
		 * @param nn
		 * @return
		 */
		private boolean inRow(int n, int nn){
			boolean wert = false;
			if (nn>n){
				if(nn%n == 0){
					wert = true;
				}else{
					wert = false;
				}
			}else if (nn<n){
				if(n%nn == 0){
					wert = true;
				}else{
					wert = false;
				}
			}else if (nn == n){ wert =  true;}
			return wert;
		}//inRow(int n, int nn)
		
	}//class
