package com.game.data;

import java.util.HashMap;
import java.util.Map;

/**
 * Room timer class
 * 
 * 
 */
public class Timer {
	private volatile boolean	_start;
	private int					_time;
	private long				_lastTime;
	private ITaskHandler		_task;
	public Map<Object, Object>	parameters;

	/**
	 * 
	 * @param time 单位毫秒
	 * @param task
	 */
	public Timer(int time, ITaskHandler task) {
		_lastTime = System.currentTimeMillis();
		_time = time;
		_task = task;
		this.parameters = new HashMap<Object, Object>();
	}

	void start() {
		if (_start)
			return;
		_start = true;
	}

	public void restart() {
		_lastTime = System.currentTimeMillis();
		start();
	}
	
	void executeTask() {
		if (!_start)
			return;
		if (System.currentTimeMillis() - _lastTime >= _time) {
			_start = false;
			if (_task != null) {
				_task.doTask(this);
			}
		}
	}

	/**
	 * 获取倒计时,单位毫秒
	 * 
	 * @return
	 */
	public int getCountdownTime() {
		return (int) (_time - (System.currentTimeMillis() - _lastTime));
	}

	public void stop() {
		if (!_start)
			return;
		_start = false;
	}

	public boolean isRuning() {
		return _start;
	}

	public interface ITaskHandler {

		public void doTask(Timer timer);
	}
}
