package ui.view;

import javax.swing.JLabel;

public class LabelHint implements Runnable {

	private JLabel label;
	private String original;
	private int remainingTime, defaultTime;
	private static final int DEFAULT_TIME=1000,//milliseconds
							 DELAY=50;
	private boolean running=false,
					keepLength=true;
	
	public LabelHint(JLabel label){
		this(label, DEFAULT_TIME);
	}
	
	public LabelHint(JLabel label, int ms){
		this.label=label;
		original=label.getText();
		this.defaultTime=ms;
		setRemaining(ms);
	}
	
	public void go(String hint){
		//the keepLengthStuff should maybe be done by the caller
		if(keepLength&&hint.length()<original.length()){
			boolean right=true;
			while(hint.length()<original.length()){
				if(right)hint=hint+' ';
				else hint=' '+hint;
				right=!right;
			}
		}
		label.setText(hint);
		setRemaining(defaultTime);
		if(!running){
			running=true;
			new Thread(this).start();
		}
	}
	
	public void go(String hint, int ms){
		setRemaining(ms);
		go(hint);
	}
	private void setRemaining(int ms) {
		remainingTime=ms/DELAY;
	}
	
	public void setKeepLength(boolean b){
		keepLength=b;
	}

	@Override
	public void run() {
		while(running){
			remainingTime--;
			if(remainingTime==0)running=false;
			try {
				Thread.sleep(DELAY);
			} catch (InterruptedException e) {}
		}
		//This is supposed to catch one-in-a-million
		//cases of Thread anomalies.
		if(remainingTime!=0)go(label.getText());
		else label.setText(original);
	}

	public void reset() {
		label.setText(original);
	}
}
