package senac_turma02.calcpol;

import java.util.Scanner;

import senac_turma02.stack.StackEmptyException;
import senac_turma02.stack.StackFactory;
import senac_turma02.stack.StackFullException;
import senac_turma02.stack.StackImpl;


public class CalculadoraPolonesa {
	/////////////////////////
	// Teste da implementacao
	/////////////////////////
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		StackFactory<Float> fact = new StackFactory<Float>();
		StackImpl<Float> s = fact.create("ARRAY", 10);
		//StackImpl<Float> s = fact.create("LE");

		String line;
		char op;
		Scanner entrada = new Scanner(System.in);

		System.out.println(" -> Digite Operador ou Operado ou F para encerrar ");
		line = entrada.next().trim();
		op = getOperador(line);
		while(!line.equalsIgnoreCase("F"))
		{
			try {
				switch(op) 	{
				case '*':
					multiply(s);
					break;
				case '/':
					divide(s);
					break;
				case '+':
					add(s);
					break;
				case '-':
					sub(s);
					break;
				default:
					getOperando(s, line);
				}
			} catch (StackFullException e) {
				e.printStackTrace();
			} catch (StackEmptyException e) {
				e.printStackTrace();
			}
			System.out.println(" -> Digite Operador ou Operado ou F para encerrar ");
			line = entrada.next();
			op = getOperador(line);
		}
		System.out.println(" -> Bye ..... ");
	}

	private static char getOperador(String line) {
		char op;
		op = line.charAt(0);
		return op;
	}

	private static void getOperando(StackImpl<Float> s, String line)
	throws StackFullException {
		float valor;
		try {
			valor = Float.parseFloat(line);
			s.push(valor);
		}
		catch( NumberFormatException ex ) {
			System.out.println(" -> Operando Invalido !!! ");			
		}
	}

	private static void sub(StackImpl<Float> s) throws StackFullException,
	StackEmptyException {

		float n1=0, n2=0;		

		if( !s.isEmpty() ) {
			n1 = s.pop();
		} 
		else {
			System.out.println("Falta operando1 !!! ");
			return;
		}

		if( !s.isEmpty() ) {
			n2 = s.pop();
		}
		else {
			s.push(n1);
			System.out.println("Falta operando2 !!! ");
			return;
		}

		if( !s.isFull() ) {
			s.push(n1 - n2);
			System.out.println("Valor do topo " + s.top());
		}
		else {
			System.out.println("Pilha Cheia !!! ");
		}
	}

	private static void add(StackImpl<Float> s) throws StackFullException,
	StackEmptyException {
		s.push(s.pop() + s.pop());
		System.out.println("Valor do topo " + s.top());
	}

	private static void divide(StackImpl<Float> s) throws StackFullException,
	StackEmptyException {
		s.push(s.pop() / s.pop());
		System.out.println("Valor do topo " + s.top());
	}

	private static void multiply(StackImpl<Float> s) throws StackFullException,
	StackEmptyException {
		s.push(s.pop() * s.pop());
		System.out.println("Valor do topo " + s.top());
	}
}
