package kr.gui;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.Dictionary;
import java.util.Hashtable;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;

import kr.gui.util.MilliTimeLabelTable;
import kr.util.audio.GainAudioClip;
import kr.util.audio.MixerAudioClip;

public class GainPanel extends JPanel
{

	private static final Dictionary<Integer, JComponent> PERCENT_TABLE = new Hashtable<Integer, JComponent>();
	
	static {
		for(int i = 0; i <= 100; i+=50)
		{
			PERCENT_TABLE.put(i, new JLabel(i+""));
		}
	}

	MixerAudioClip mixer;

	public void init(MixerAudioClip mixer)
	{
		this.mixer = mixer;
		removeAll();
		setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.fill = c.BOTH;
		c.weighty = 0; c.weightx = 1;
		c.gridx = c.gridy = 0;
		
		for(int i = 0; i < mixer.getNumLines(); i++)
		{
			if(!mixer.isLineHidden(i))
			{
				SubPanel s;
				add(s=new SubPanel(i),c);
				c.gridx++;
				createController(s);
			}
		}
	}
	
	/**
	 * May be overridden.
	 */
	protected void createController(SubPanel subPanel)
	{
		new GainSubPanelController(this, subPanel, subPanel.getLineNumber());
	}

	public class SubPanel extends JPanel
	{ 
		private JSlider slider;
		private JCheckBox mutedCheckBox;
		private int lineNumber;
		
		
		public SubPanel(int lineNumber) {
			this.lineNumber = lineNumber;
			init();
		}

		public int getLineNumber() {
			return lineNumber;
		}

		private void init()
		{
			setLayout(new GridBagLayout());
			GridBagConstraints c = new GridBagConstraints();
			c.fill = c.BOTH;
			c.weightx = c.weighty = 0;
			c.gridy=0;
			String name = mixer.getName(lineNumber);
			add(new JLabel(name != null ? name : "Foo"),c);
			
			c.weighty = 0;
			c.weightx = 1;
			c.gridy++;
	        slider = new JSlider(JSlider.HORIZONTAL,
                    0, 100, 0);
	        //slider.setLabelTable(PERCENT_TABLE);
			//slider.setPaintLabels(true);
			slider.setMajorTickSpacing(10);
			slider.setMinorTickSpacing(5);
			slider.setPaintTicks(true); 

			add(slider,c);
			
			c.weighty = 0;
			c.gridy++;

			mutedCheckBox = new JCheckBox("Mute");

			add(mutedCheckBox,c);
			
			updateSettings();
		}

		public void updateSettings()
		{
			mutedCheckBox.setSelected(mixer.isMutedFlag(lineNumber));
			slider.setValue(Math.round(mixer.getVolume(lineNumber) * 100));
		}

		public JCheckBox getMutedCheckBox() {
			return mutedCheckBox;
		}

		public JSlider getSlider() {
			return slider;
		}
	}
}

