package kr.gui.util;

import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;

import javax.swing.JComponent;
import javax.swing.JLabel;

public class MilliTimeLabelTable extends Dictionary<Integer, JComponent> {
	
	private int milliSpacing;
	
	private static final int MAX_SIZE = 10 * 60 * 1000;
	
	private HashMap<Integer, JComponent> cache = new HashMap<Integer, JComponent>(); //PERF: consider using a List

	public MilliTimeLabelTable(int milliSpacing)
	{
		this.milliSpacing = milliSpacing;
	}

	public int size() {
		return MAX_SIZE / milliSpacing;
	}

	public boolean isEmpty() {
		return false;
	}

	public Enumeration keys() {
		return new KeysEnumeration();
	}

	public Enumeration elements() {
		return new ValuesEnumeration();
	}

	public JComponent get(Object key) {
		return getLabel((Integer)key);
	}

	/**
	 * No-op
	 */
	public JComponent put(Integer key, JComponent value) {
		return null;
	}

	/**
	 * No-op
	 */
	public JComponent remove(Object key) {
		return null;
	}
	
	private JComponent getLabel(Integer pos)
	{
		JComponent l = cache.get(pos);
		
		if(l == null)
		{
			l =  new JLabel(String.format("%d:%02d", pos/1000/60, (pos/1000) % 60));
			cache.put(pos, l);
		}
		
		return l;
	}

	class KeysEnumeration implements Enumeration
	{
		private int pos = 0;
		public boolean hasMoreElements() {
			return MAX_SIZE - milliSpacing > pos;
		}

		public Object nextElement() {
			pos += milliSpacing;
			
			return new Integer(pos - milliSpacing);
		}
	}

	class ValuesEnumeration implements Enumeration
	{
		private int pos = 0;
		public boolean hasMoreElements() {
			return MAX_SIZE - milliSpacing > pos;
		}

		public Object nextElement() {
			JComponent label = getLabel(pos);
			pos += milliSpacing;
			return label;
		}
	}
}
