package calculator;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
 
public class JShell extends JPanel implements KeyListener {
 
    private static final long serialVersionUID = 1L;
 
    JTextField field = new JTextField();
    JEditorPane editor = new JEditorPane();
 
    public JShell() {
        super(new BorderLayout());
 
        // Content
        editor.setEditable(false);
        editor.setBackground(Color.LIGHT_GRAY);
        this.add(editor, BorderLayout.CENTER);
 
        field.addKeyListener(this);
        this.add(field, BorderLayout.PAGE_END);
    }
 
    @Override
    public void keyTyped(KeyEvent e) {
 
    }
 
    @Override
    public void keyPressed(KeyEvent e) {
 
    }
 
    @Override
    public void keyReleased(KeyEvent e) {
        // Wenn Enter gedr�ckt wird, wird die Eingabe in
        // editor �bernommen und field geleert
        if (e.getKeyCode() == KeyEvent.VK_ENTER) {
            editor.setText(editor.getText() + field.getText() + "\n");
            field.setText("");
            runCommand(field.getText());
        }
 
    }
 
    public static void main(String[] args) {
        // GUI starten
        setUp();
    }
 
    public static void setUp() {
        // Frame
        JFrame frame = new JFrame("JShell");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(600, 300);
 
        JPanel panel = new JShell();
        frame.setContentPane(panel);
 
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    
    public abstract class Command {
        public Command() {
            super();
        }
        public abstract void run(String... args);
    }

    public class HelloWorldCommand extends Command {
        public HelloWorldCommand(){
            super();
        }
        @Override
		public void run(String... args) {
            System.out.println("Hello World");
        }
        @Override
		public String toString() {
            return("HelloWorld");
        }
    }
     
    private Map<String, Command> commandMap = new HashMap<String, Command>();

    public void loadCommands() {
        Command cmd = new HelloWorldCommand();
        commandMap.put(cmd.toString(), cmd);
    }
    
    public void runCommand(String line) {
        String[] split = Pattern.compile(" ").split(line, 0);
        Command cmd = commandMap.get(split[0]);
        if(cmd != null)
            cmd.run(split); //Erstes Parameter entfernen?
        else
            System.out.println("Befehl nicht gefunden"); //Zuerst auf lokale Anwendung pr�fen?
    }
    
}