/*
Copyright (C) 2005 David Green <green@couchpotato.net>
All Rights Reserved.

This file is part of Aelfengard.

Aelfengard is proprietary software. You may not redistribute it without
prior written permission from the copyright holder.
*/

package common.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.ScrollPaneConstants;

import common.ScriptType;


/**
 * The scripting console window.
 * 
 * @author David Green <green@couchpotato.net>
 */
public class ConsoleWindow extends JFrame {
    
    private static final long serialVersionUID = 1L;
    private static final String DEFAULT_TITLE = "Scripting Console";

    private final int consoleId;
    private final ScriptType scriptType;
    private final String filename;
    
    private final JTextArea inputArea = new JTextArea();
    private final JTextArea outputArea = new JTextArea();

    /**
     * Creates a new console window.
     * 
     * @param consoleId the console id
     * @param scriptType the script scriptType
     * @param filename the filename
     * @param text the script text
     */
    public ConsoleWindow(int consoleId, ScriptType scriptType, String filename, String text) {
        super(DEFAULT_TITLE + " - " + scriptType + " " + filename);

        this.consoleId = consoleId;
        this.scriptType = scriptType;
        this.filename = filename;
        
        initMenus();
        
        outputArea.setEditable(false);
        outputArea.setBackground(new Color(230, 230, 230));
        
        outputArea.setLineWrap(true);
        outputArea.setWrapStyleWord(true);
        
        JScrollPane inputScroller = new JScrollPane(inputArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        JScrollPane outputScroller = new JScrollPane(outputArea, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, inputScroller, outputScroller);
        splitPane.setDividerLocation(0.5);
        splitPane.setResizeWeight(0.5);
        add(splitPane, BorderLayout.CENTER);
        
        setSize(640, 480);
        
        if (text != null) {
            inputArea.setText(text);
        }
        
    }
    
    public void write(String text) {
        outputArea.setText(text);
    }
    
    private void initMenus() {
        JMenuItem executeItem = new JMenuItem("Execute");
        executeItem.setMnemonic('e');
        executeItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0));

        JMenuItem saveItem = new JMenuItem("Save...");
        saveItem.setMnemonic('s');
        saveItem.setAccelerator(KeyStroke.getKeyStroke(new Character('S'), InputEvent.CTRL_DOWN_MASK));
        
        JMenuItem exitItem = new JMenuItem("Exit");
        exitItem.setMnemonic('x');
        
        JMenu fileMenu = new JMenu("File");
        fileMenu.setMnemonic('f');
        fileMenu.add(executeItem);
        fileMenu.add(saveItem);
        fileMenu.add(exitItem);
        
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(fileMenu);
        
        setJMenuBar(menuBar);
        
        exitItem.addActionListener(new ActionListener() {
        
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        
        });
        
        executeItem.addActionListener(new ActionListener() {
        
            public void actionPerformed(ActionEvent e) {
                outputArea.setText("*****************\n*** Executing ***\n*****************");
                String text = inputArea.getText();
                StringBuffer output = new StringBuffer();
                try {
                    BufferedReader reader = new BufferedReader(new StringReader(text));
                    while (true) {
                        String line = reader.readLine();
                        if (line == null) {
                            break;
                        }
                        if (line.startsWith("//&")) {
                            line = line.substring(3);
                        }
                        output.append(line).append('\n');
                    }
                }
                catch (IOException ex) {
                    throw new RuntimeException(ex); // doesn't happen with StringReader
                }
                GameClient.executeManualScript(consoleId, scriptType, output.toString());
            }
        
        });
        
        saveItem.addActionListener(new ActionListener() {
        
            public void actionPerformed(ActionEvent e) {
                GameClient.saveScript(consoleId, scriptType, filename, inputArea.getText());
            }
        
        });

    }
    
    public int getConsoleId() {
        return consoleId;
    }
    
    public void saveResponse(boolean error, String msg) {
        JOptionPane.showMessageDialog(this, msg, error ? "Error" : "Success", error ? JOptionPane.ERROR_MESSAGE : JOptionPane.INFORMATION_MESSAGE);
    }
    
}