package jp.sourceforge.acerola3d.a3panels;

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

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.MalformedURLException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class BVHPanel extends JPanel implements ActionListener, ChangeListener {
    private static final long serialVersionUID = 1L;
    JMenuBar menuBar;
    JMenu configMenu;
    JMenu measureMenu;
    JMenuItem measureXZMenuItem;
    JMenuItem measureXYMenuItem;
    JMenuItem measureYZMenuItem;
    JMenuItem measureNoneMenuItem;
    A3Canvas a3canvas;
    JButton resetViewButton;
    JCheckBox defaultPoseCheckBox;
    JComboBox boneComboBox;
    JLabel statusBarLabel;
    JCheckBox pauseCheckBox;
    JSlider slider;
    int sliderLength=100;
    double motionLength;
    Action3D measure;

    Skeleton skeleton;
    String actionName = "0";
    MyExamController controller;
    ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);

    public BVHPanel(final String urlString) {
        setLayout(new BorderLayout());
        MyVBox baseBox = new MyVBox();
        this.add(baseBox,BorderLayout.CENTER);

        MyHBox mainBox = new MyHBox();
        baseBox.myAdd(mainBox,1.0);

        a3canvas = A3Canvas.createA3Canvas(300,300);
        a3canvas.setPreferredSize(new Dimension(300,300));
        controller = new MyExamController();
        a3canvas.setA3Controller(controller);
        mainBox.myAdd(a3canvas,1.0);

        MyVBox controlBox = makeControlBox();
        mainBox.myAdd(controlBox,0.0);

        Box box3 = Box.createHorizontalBox();
        baseBox.myAdd(box3,0.0);
        pauseCheckBox = new JCheckBox("puase");
        pauseCheckBox.setSelected(false);
        pauseCheckBox.addActionListener(this);
        box3.add(pauseCheckBox);
        slider = new JSlider();
        slider.setMinimum(0);
        slider.setMaximum(sliderLength);
        slider.addChangeListener(this);
        box3.add(slider);

        statusBarLabel = new JLabel("Status:");
        baseBox.myAdd(statusBarLabel,0.0);

        try {
            Action3D.clearCash("x-res:///jp/sourceforge/acerola3d/a3panels/resources/measure.a3");
            measure = new Action3D("x-res:///jp/sourceforge/acerola3d/a3panels/resources/measure.a3");
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (urlString!=null) {
            Runnable r = new Runnable() {
                public void run() {
                    loadBVH(urlString);
                }
            };
            executor.schedule(r,100,TimeUnit.MILLISECONDS);
        }
    }

    MyVBox makeControlBox() {
        MyVBox controlBox = new MyVBox();

        menuBar = new JMenuBar();
        controlBox.myAdd(menuBar,0.0);
        menuBar.add(Box.createHorizontalGlue());
        configMenu = new JMenu("Config");
        menuBar.add(configMenu);
        measureMenu = new JMenu("measure");
        configMenu.add(measureMenu);
        measureXZMenuItem = new JMenuItem("measure XZ");
        measureXZMenuItem.addActionListener(this);
        measureMenu.add(measureXZMenuItem);
        measureXYMenuItem = new JMenuItem("measure XY");
        measureXYMenuItem.addActionListener(this);
        measureMenu.add(measureXYMenuItem);
        measureYZMenuItem = new JMenuItem("measure YZ");
        measureYZMenuItem.addActionListener(this);
        measureMenu.add(measureYZMenuItem);
        measureNoneMenuItem = new JMenuItem("measure None");
        measureNoneMenuItem.addActionListener(this);
        measureMenu.add(measureNoneMenuItem);

        resetViewButton = new JButton("Reset View");
        resetViewButton.addActionListener(this);
        controlBox.myAdd(resetViewButton,0.0);

        defaultPoseCheckBox = new JCheckBox("default pose");
        defaultPoseCheckBox.setSelected(false);
        defaultPoseCheckBox.addActionListener(this);
        controlBox.myAdd(defaultPoseCheckBox,0.0);

        boneComboBox = new JComboBox();
        boneComboBox.addActionListener(this);
        boneComboBox.addItem("[none]");
        controlBox.myAdd(boneComboBox,0.0);

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

        controlBox.myAdd(Box.createVerticalGlue(),1.0);

        return controlBox;
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == resetViewButton) {
        	controller.adjust(skeleton);
        } else if (ae.getSource() == defaultPoseCheckBox) {
        	if (defaultPoseCheckBox.isSelected())
        	    skeleton.defaultPose();
        	else
        		skeleton.start();
        } else if (ae.getSource() == measureXZMenuItem) {
            measure.setRot(-Math.PI/2.0,0.0,0.0);
            a3canvas.add(measure);
        } else if (ae.getSource() == measureXYMenuItem) {
            measure.setRot(0.0,0.0,0.0);
            a3canvas.add(measure);
        } else if (ae.getSource() == measureYZMenuItem) {
            measure.setRot(0.0,Math.PI/2.0,0.0);
            a3canvas.add(measure);
        } else if (ae.getSource() == measureNoneMenuItem) {
            a3canvas.del(measure);
        } else if (ae.getSource() == pauseCheckBox) {
            if (skeleton == null)
                return;
            if (pauseCheckBox.isSelected()) {
            	skeleton.pause();
                double t = motionLength*((double)slider.getValue()/(double)sliderLength);
                skeleton.setPauseTime(t);
            } else {
                skeleton.start();
                double t = motionLength*((double)slider.getValue()/(double)sliderLength);
                skeleton.setPauseTime(t);
            }
        } else if (ae.getSource() == boneComboBox) {
        	selectBone();
        } else {
            System.out.append("gaha???");
        }
    }
    void selectBone() {
    	String bn = (String)boneComboBox.getSelectedItem();
if (bn==null) {
System.out.println("gaha1");
return;
}
    	if (bn.equals("[none]")) {
    		resetBone();
    	} else {
    		resetBone();
    	    skeleton.setBoneSelected(bn,true);
    	}
    	
    }
    void resetBone() {
    	if (skeleton==null)
    		return;
    	skeleton.resetSelected();
    }

	@Override
	public void stateChanged(ChangeEvent ce) {
        if (ce.getSource()==slider) {
            if (skeleton==null)
                return;
            double t = motionLength*((double)slider.getValue()/(double)sliderLength);
            skeleton.setPauseTime(t);
        }
	}

	void loadBVH(String urlString) {
        statusBarLabel.setText("Status: Loading ... ");
        statusBarLabel.repaint();
        if (skeleton!=null)
            a3canvas.del(skeleton);
        try {
            A23.initA23();
            skeleton = new Skeleton(urlString);
            controller.adjust(skeleton);
        } catch(Exception e) {
            System.out.println("J3DVrml.loadVRML. error!");
            e.printStackTrace();
        }
        a3canvas.add(skeleton);

        boneComboBox.removeAllItems();
        boneComboBox.addItem("[none]");
        for (String bn:skeleton.getBones()) {
        	boneComboBox.addItem(bn);
        }
        if (pauseCheckBox.isSelected()) {
        	skeleton.pause();
        } else {
        	skeleton.start();
        }
        slider.setValue(0);
        motionLength = skeleton.getMotionLength();

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

        Runnable r = new Runnable() {
            public void run() {
                controller.adjust(skeleton);
            }
        };
        executor.schedule(r,100,TimeUnit.MILLISECONDS);

        statusBarLabel.setText("Status: Loading ... done.");
    }
    public void loadBVH(File f) {
        try {
            final String urlString = f.toURI().toURL().toString();
            Runnable r = new Runnable() {
                public void run() {
                    loadBVH(urlString);
                }
            };
            executor.schedule(r,100,TimeUnit.MILLISECONDS);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
