package calculette;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

@Exercice(5)
public class Controleur implements ActionListener{
	public final static long serialVersionUID = 1L;

	private double v1=0;
	private char op='+';
	private boolean mem=true;
	private boolean hasDot=false;
	
	private StringBuilder sb=new StringBuilder();
	
	private Ecran ecran;
	
	public Controleur(Ecran ecran){
		this.ecran = ecran;
	}
	
	@Exercice(6)
	private void calcul(){
		switch(op){
		case '+' : v1+=Double.valueOf(sb.toString()); break;
		case '-' : v1-=Double.valueOf(sb.toString());break;
		case '/' : v1/=Double.valueOf(sb.toString());break;
		case '*' : v1*=Double.valueOf(sb.toString());break;
		}
	}
	
	@Exercice(6)
	public void actionPerformed(ActionEvent e) {
		Touche t=(Touche) e.getSource();
		switch(t.ct){
		case '+' :
		case '-' :
		case '/' :
		case '*' :
			if(mem) 
			calcul();
			else{
				v1=Double.valueOf(sb.toString());
				mem=true;
			}
			op=t.ct;
			sb=new StringBuilder();
			hasDot=false;
			ecran.setText(String.valueOf(v1));
			break;
		case '=' :
			if(mem)
				calcul();
			else 
				v1=Double.valueOf(sb.toString());
			mem=false;
			sb=new StringBuilder();
			hasDot=false;
			ecran.setText(String.valueOf(v1));
			break;
		case '.' : if(hasDot) break; else hasDot=true;
		default :
			sb.append(t.ct);
			ecran.setText(sb.toString());
		}
	}

	
}
