package calculator;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
import javax.swing.text.BadLocationException;


public class Console extends JFrame{

	JTextArea txp = new JTextArea();
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -4662212357842559736L;

	public Console(){
        super("Console");
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		addWindowListener(new WindowAdapter(){
			@Override
			public void windowClosing(WindowEvent e){System.exit(0);}
		});
//		txp.setCaretPosition(txp.getText().length());
		txp.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				super.keyPressed(e);
				if(e.getKeyCode() == KeyEvent.VK_ENTER){
					String sText = txp.getText();
					String text;
					txp.setCaretPosition(sText.length());
					//txp.get;
					int start, end, lines;
		            lines = txp.getLineCount();
					System.out.print(lines+": ");
					try {
			            start = txp.getLineStartOffset(lines-1);
			            end = txp.getLineEndOffset(lines-1);
//			            line = txp.getLineOfOffset(25);
						text = txp.getText(start, end-start);
						text = text.replaceAll("\\s+", "");
//						System.out.println(sText);
						
						String[] p;
				    	p = text.split("\\+");
				    	double result=0;
				    	if(p.length>1){
				    		int i;
				    		for(i=0; i<p.length; i++){
				    			if(isNumber(p[i])){
						    		try{
						    			result += Double.valueOf(p[i]);
						    		} catch(Exception ex){
						    			System.out.println("Exception: "+ex.getLocalizedMessage());
						    		}
				    			}
				    		}
							System.out.println(result);
				    	} else {
				    		try{
				    			result = Double.valueOf(text);
								System.out.println(result);
				    		} catch(Exception ex){
				    			System.out.println("Exception: "+ex.getLocalizedMessage());
				    		}
				    	}
				    	
				    	
				    	
				    	String output = sText+"\n"+result;
				    	txp.setText(output);
			            
			                
			        } catch(BadLocationException ex) {
						System.out.println("BadLocationException");
			        }
				}
			}
		});
		
		JScrollPane sp = new JScrollPane(txp);
		add(sp);
	}
	
	public boolean isNumber(String str){
		if(str.length() == 0) return false;
		String[] p;
		p = str.split("\\+");
		if(p.length > 1) return false;
		p = str.split("\\-");
		if(p.length > 1) return false;
		return true;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Console c = new Console();
		c.setSize(600,400);
		c.setVisible(true);
	}

}
