$package("js.lang");

/**
 * Construct a Thread.
 * @param {Integer} _Delay
 */
js.lang.Thread = function (delay){
	if(delay!=null) this.delay = delay;
} 
js.lang.Thread.prototype = new js.lang.BaseObject();

js.lang.ThreadState = {UNSTARTED:-1, TERMINATED:0, STARTED:1, RUNNABLE:2, BLOCKED:3, WAITING:4, TIMED_WAITING:5};
js.lang.ThreadPriority = {MIN_PRIORITY:1, NORM_PRIORITY:5, MAX_PRIORITY:10} ;

js.lang.Thread.prototype.priority = js.lang.ThreadPriority.MIN_PRIORITY;
js.lang.Thread.prototype.state = js.lang.ThreadState.STARTED;
js.lang.Thread.prototype.started = false;
js.lang.Thread.prototype.delay = 0;
js.lang.Thread.prototype.tid = null; 
js.lang.Thread.prototype.interrupted = false;

/**
 * Stop the Thread.
 */
js.lang.Thread.prototype.stop = function() {
	if (!(this.started)) return;
	window.clearInterval(this.tid);
	this.tid = null; 
	this.state = "TERMINATED";
	this.started = false;
	this.interrupted = false;
}

/**
 * Start the Thread.
 */
js.lang.Thread.prototype.start = function() {
	if (this.started) return;
	this.started = true;
	this.state = js.lang.ThreadState.RUNNABLE;
	this.interrupted = false;
	this.tid = window.setInterval(this.run, this.delay);  
}

/**
 * Sleep the thread
 * @param {long} _Interval
 */
js.lang.Thread.prototype.sleep = function(_interval) {	
	if (!(this.started)) return;
	if (this.interrupted) return;
	window.clearInterval(this.tid);
	this.state = js.lang.ThreadState.TIMED_WAITING;
	this.interrupted = true; 
	window.setTimeout(this.getName() + ".resume();", _interval); 
}

/**
 * Run the thread
 */
js.lang.Thread.prototype.run = function() {
}

/**
 * Suspend the thread
 */
js.lang.Thread.prototype.suspend = function() {	
	if (!(this.started)) return;	
	if (this.interrupted) return;
	window.clearInterval(this.tid);
	this.state = js.lang.ThreadState.WAITING;
	this.interrupted = true;
}

/**
 * Resume the thread
 */
js.lang.Thread.prototype.resume = function() {	
	if (!(this.started)) return;
	if (!(this.interrupted)) return; 
	this.state = js.lang.ThreadState.RUNNABLE;
	this.interrupted = false;
	this.tid = window.setInterval(this.run, this.delay);   
}
