package jp.sourceforge.acerola3d.j3dvrml;

import jp.sourceforge.acerola3d.*;
import jp.sourceforge.acerola3d.a3.*;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.URL;

import javax.swing.*;

public class J3DVrml implements ActionListener {
    JFrame frame;
    JMenuBar menuBar;
    JMenu configMenu;
    JMenuItem consoleMenuItem;
    JMenuItem proxyMenuItem;
    JMenuItem resetViewMenuItem;
    JMenuItem snapshotMenuItem;
    JMenuItem backgroundMenuItem;
    JTextField urlTextField;
    JButton refButton;
    JFileChooser fileChooser;
    A3Canvas a3canvas;
    JButton resetViewButton;
    JLabel statusBarLabel;
    JFrame consoleFrame;
    JTextArea consoleTextArea;
    JButton clearConsoleButton;

    VRML vrml;
    String actionName = "0";
    MyExamController controller;

    public J3DVrml(String args[]) {
        frame = new JFrame("J3DVrml");
        Box baseBox = Box.createVerticalBox();
        frame.getContentPane().add(baseBox);

        menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);
        menuBar.add(Box.createHorizontalGlue());
        configMenu = new JMenu("Config");
        menuBar.add(configMenu);
        consoleMenuItem = new JMenuItem("Console");
        consoleMenuItem.addActionListener(this);
        configMenu.add(consoleMenuItem);
        proxyMenuItem = new JMenuItem("Proxy");
        proxyMenuItem.addActionListener(this);
        configMenu.add(proxyMenuItem);
        resetViewMenuItem = new JMenuItem("ResetView");
        resetViewMenuItem.addActionListener(this);
        configMenu.add(resetViewMenuItem);
        snapshotMenuItem = new JMenuItem("Snapshot");
        snapshotMenuItem.addActionListener(this);
        configMenu.add(snapshotMenuItem);
        backgroundMenuItem = new JMenuItem("Background");
        backgroundMenuItem.addActionListener(this);
        configMenu.add(backgroundMenuItem);

        consoleFrame = new JFrame("Console");
        Box b = Box.createVerticalBox();
        consoleTextArea = new JTextArea(20,60);
        consoleTextArea.setEditable(false);
        JScrollPane sp = new JScrollPane(consoleTextArea);
        b.add(sp);
        clearConsoleButton = new JButton("Clear");
        clearConsoleButton.addActionListener(this);
        b.add(clearConsoleButton);
        consoleFrame.getContentPane().add(b);
        consoleFrame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                consoleFrame.setVisible(false);
            }
        });
        PrintStream systemOut = System.out;
        JTextAreaOutputStream jtaos = new JTextAreaOutputStream(consoleTextArea,systemOut);
        PrintStream ps = new PrintStream(jtaos,true);
        System.setOut(ps);
        System.setErr(ps);
        consoleFrame.pack();
        
        Box box1 = Box.createHorizontalBox();
        baseBox.add(box1);
        box1.add(new JLabel("URL:"));
        urlTextField = new JTextField();
        try {
            File f = null;
            if ((args!=null)&&(args.length==2)&&(args[0].equals("-open")))
                f  = new File(args[1]);
            else
                f = new File(args[0]);
            urlTextField.setText(f.toURI().toString());
        } catch (Exception e) {
            urlTextField.setText("x-res:///jp/sourceforge/acerola3d/j3dvrml/resources/Acerola3D.wrl");
        }
        urlTextField.addActionListener(this);
urlTextField.setMaximumSize(new Dimension(3000,30));
        box1.add(urlTextField);
        refButton = new JButton("ref");
        refButton.addActionListener(this);
        box1.add(refButton);

        Box box2 = Box.createHorizontalBox();
        baseBox.add(box2);

        a3canvas = A3Canvas.createA3Canvas(300,300);
        controller = new MyExamController();
        a3canvas.setA3Controller(controller);
        box2.add(a3canvas);

        Box controlBox = makeControlBox();
        box2.add(controlBox);

        statusBarLabel = new JLabel("Status:");
        baseBox.add(statusBarLabel);

        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent we) {
                frame.dispose();
                System.exit(0);
            }
        });
        frame.pack();
        frame.setVisible(true);

        loadVRML();
    }

    Box makeControlBox() {
        Box controlBox = Box.createVerticalBox();

        resetViewButton = new JButton("Reset View");
        resetViewButton.addActionListener(this);
        controlBox.add(resetViewButton);

        controlBox.add(new JLabel("Left drag: rotation"));
        controlBox.add(new JLabel("Center drag: translation"));
        controlBox.add(new JLabel("Right drag: scale"));

        controlBox.add(Box.createVerticalGlue());

        String buildTime = null;
        try {
            URL url = getClass().getClassLoader().getResource("buildTime.txt");
            InputStreamReader isr = new InputStreamReader(url.openStream(),"UTF-8");
            BufferedReader br = new BufferedReader(isr);
            buildTime = br.readLine();
        } catch (Exception e) {
            buildTime = "???";
        }
        controlBox.add(new JLabel("build time:"));
        controlBox.add(new JLabel("   "+buildTime));

        return controlBox;
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == urlTextField) {
            loadVRML();
        } else if (ae.getSource() == resetViewButton) {
        	controller.reset(vrml);
        } else if (ae.getSource() == refButton) {
            ref();
        } else if (ae.getSource() == consoleMenuItem) {
            consoleFrame.setVisible(true);
        } else if (ae.getSource() == clearConsoleButton) {
            consoleTextArea.setText("");
        } else if (ae.getSource() == proxyMenuItem) {
            proxyConfig();
        } else if (ae.getSource() == resetViewMenuItem) {
        	controller.reset(vrml);
        } else if (ae.getSource() == snapshotMenuItem) {
            try {
                File f = new File("snapshot.png");
                a3canvas.saveImage(f);
            } catch (Exception e) {
                System.out.println("A3Viewer:snapshot");
                e.printStackTrace();
            }
        } else if (ae.getSource() == backgroundMenuItem){
            setBackground();
        } else {
            System.out.append("gaha???");
        }
    }

    void loadVRML() {
        statusBarLabel.setText("Status: Loading ... ");
        statusBarLabel.repaint();
        if (vrml!=null)
            a3canvas.del(vrml);
        String urlString = urlTextField.getText();
        try {
            A23.initA23();
            vrml = VRML.load(urlString);
            controller.reset(vrml);
        } catch(Exception e) {
            System.out.println("J3DVrml.loadVRML. error!");
            e.printStackTrace();
        }
        a3canvas.add(vrml);

        vrml.setLocImmediately(0.0,0.0,0.0);
        vrml.setQuatImmediately(0.0,0.0,0.0,1.0);
        vrml.setScaleImmediately(1.0);

        statusBarLabel.setText("Status: Loading ... done.");
    }

    ProxyPanel proxyPanel = null;
    String proxyData[] = {"","","",""};
    void proxyConfig() {
        if (proxyPanel == null) {
            proxyPanel = new ProxyPanel();
            proxyData[0] = System.getProperty("proxyHost");
            proxyData[1] = System.getProperty("proxyPort");
            proxyData[2] = System.getProperty("ftpProxyHost");
            proxyData[3] = System.getProperty("ftpProxyPort");
        }
        proxyPanel.setData(proxyData);

        Object options[] = {"Ok","Cancel"};
        int result = JOptionPane.showOptionDialog(frame,proxyPanel,"proxy",
                                                  JOptionPane.DEFAULT_OPTION,
                                                  JOptionPane.INFORMATION_MESSAGE,
                                                  null,options,options[0]);
        if (result==0) {
            proxyData = proxyPanel.getData();
            if (!proxyData[0].equals("")) {
                System.getProperties().put("proxySet","true");
                System.getProperties().put("proxyHost",proxyData[0]);
                System.getProperties().put("proxyPort",proxyData[1]);
            } else {
                System.getProperties().put("proxySet","false");
                System.getProperties().put("proxyHost","");
                System.getProperties().put("proxyPort","");
            }
            if (!proxyData[2].equals("")) {
                System.getProperties().put("ftpProxySet","true");
                System.getProperties().put("ftpProxyHost",proxyData[2]);
                System.getProperties().put("ftpProxyPort",proxyData[3]);
            } else {
                System.getProperties().put("ftpProxySet","false");
                System.getProperties().put("ftpProxyHost","");
                System.getProperties().put("ftpProxyPort","");
            }
        }
    }

    class ProxyPanel extends JPanel {
        private static final long serialVersionUID = 1L;
        JTextField httpHostTF;
        JTextField httpPortTF;
        JTextField ftpHostTF;
        JTextField ftpPortTF;

        public ProxyPanel() {
            Box b0 = Box.createVerticalBox();
            Box b1 = Box.createHorizontalBox();
            Box b2 = Box.createHorizontalBox();

            this.add(b0);
            b0.add(b1);
            b0.add(b2);

            b1.add(new JLabel("http: host"));
            httpHostTF = new JTextField(40);
            b1.add(httpHostTF);
            b1.add(new JLabel(" port "));
            httpPortTF = new JTextField(5);
            b1.add(httpPortTF);

            b2.add(new JLabel("ftp: host"));
            ftpHostTF = new JTextField(40);
            b2.add(ftpHostTF);
            b2.add(new JLabel(" port "));
            ftpPortTF = new JTextField(5);
            b2.add(ftpPortTF);
        }

        public void setData(String proxyData[]) {
            httpHostTF.setText(proxyData[0]);
            httpPortTF.setText(proxyData[1]);
            ftpHostTF.setText(proxyData[2]);
            ftpPortTF.setText(proxyData[3]);
        }

        public String[] getData() {
            String ret[] = new String[4];
            ret[0] = httpHostTF.getText();
            ret[1] = httpPortTF.getText();
            ret[2] = ftpHostTF.getText();
            ret[3] = ftpPortTF.getText();
            return ret;
        }
    }

    void ref() {
        if (fileChooser == null) {
            fileChooser = new JFileChooser(".");
        }
        int returnVal = fileChooser.showOpenDialog(frame);
        if(returnVal != JFileChooser.APPROVE_OPTION)
            return;

        File f = fileChooser.getSelectedFile();
        URL url = null;
        try{url=new URL(f.toURI().toString());}catch(Exception e){;}
        if (url == null)
            return;
        urlTextField.setText(url.toExternalForm());
        loadVRML();
    }
    void setBackground() {
        if (fileChooser == null) {
            fileChooser = new JFileChooser(".");
        }
        int returnVal = fileChooser.showOpenDialog(frame);
        if (returnVal != JFileChooser.APPROVE_OPTION)
            return;

        File f = fileChooser.getSelectedFile();
        URL url = null;
        try{url=new URL(f.toURI().toString());}catch(Exception e){;}
        if (url == null)
            return;
        Action3D a = null;
        try{
            a = Action3D.load(url);
        } catch(Exception e) {
            e.printStackTrace();
        }
        if (a!=null)
            a3canvas.setBackground(a);
    }

    public static void main(String args[]) {
        // セキュリティマネージャが、
        // LinuxのJava Web Startの時だけ
        // Exceptionを出すので、とりあえずnullに
        // しておく。
        System.setSecurityManager(null);
        final String argsCopy[] = args;
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new J3DVrml(argsCopy);
            }
        });
    }
}
