package adecWatt.view;

// XXX still magics values

import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JToolBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import misc.Bundle;

@SuppressWarnings ("serial") public class JWorkspaceSlidersToolBar extends JToolBar implements ChangeListener {

    JWorkspaceView<?> jWorkspaceView;
    JPanel jSet = new JPanel ();
    JSlider jScale = new JSlider (0, 200, 100);
    JSlider jOpacity = new JSlider (0, 200, 100);
    
    public JWorkspaceSlidersToolBar (JAdecWatt jAdecWatt) {
	super ("Slider");
	add (jSet);
	jScale.setMajorTickSpacing (50);
	jScale.setMinorTickSpacing (10);
	jSet.add (jScale);
	jSet.add (jOpacity);
	setJWorkspaceView (null);
	jScale.addChangeListener (this);
	jOpacity.addChangeListener (this);
	jAdecWatt.stateNotifier.addUpdateObserver (this, JAdecWatt.BroadcastChangeScale);
	// XXX jAdecWatt.stateNotifier.addUpdateObserver (this, JAdecWatt.BroadcastChangeOpacity);
	jScale.setToolTipText (Bundle.getAction ("Scale"));
	jOpacity.setToolTipText (Bundle.getAction ("Crossfades"));
    }
    public void setOrientation (int o) {
	if (jScale != null) {
	    jScale.setOrientation (o);
	    jOpacity.setOrientation (o);
	    jSet.setLayout (new BoxLayout (jSet, o == HORIZONTAL ? BoxLayout.Y_AXIS : BoxLayout.X_AXIS));
	}
	super.setOrientation (o);
    }
    public void setJWorkspaceView (JWorkspaceView<?> jWorkspaceView) {
	this.jWorkspaceView = jWorkspaceView;
	if (jWorkspaceView == null) {
	    jScale.setEnabled (false);
	    jOpacity.setEnabled (false);
	    jOpacity.setValue (100);
	} else {
	    jScale.setEnabled (true);
	    if (jWorkspaceView.workspace.getBuilding () != null) {
		jOpacity.setEnabled (true);
		jOpacity.setValue ((int) (jWorkspaceView.workspace.getOpacity ()*200));
	    } else
	    jOpacity.setValue (100);
	}
	updateChangeScale ();
    }
    public void stateChanged (ChangeEvent e) {
	if (jWorkspaceView == null)
	    return;
	if (e.getSource () == jScale) {
	    jWorkspaceView.setScale (Math.pow (10, jScale.getValue ()/100.-1)*jWorkspaceView.getInitScale ());
	    return;
	}
	jWorkspaceView.workspace.setOpacity (jOpacity.getValue ()/200F);
	jWorkspaceView.repaint ();
    }

    public void updateChangeScale () {
	if (jWorkspaceView == null) {
	    jScale.setValue (100);
	    return;
	}
        jScale.removeChangeListener (this);
        jScale.setValue ((int) (100*(Math.log10 (jWorkspaceView.getScale ()/jWorkspaceView.getInitScale ())+1)));
        jScale.addChangeListener (this);
    }
}
