package com.game.state;

import com.game.Global;

/**
 * 状态机
 * 
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class StateMachine {

	private Object		owner		= null;
	/**
	 * 当前状态
	 */
	public StateBase	curState	= null;
	public StateBase	lastState	= null;

	public StateMachine(Object owner) {
		this.owner = owner;
	}

	/**
	 * 改变状态
	 * @param state
	 */
	public void changeState(StateBase state) {
		if (curState != null) {
			this.curState.exit(this.owner);
		}
		if (this.lastState != this.curState) {
			this.lastState = this.curState;
		}
		if (Global.loggerDebug) {
			String old_log = this.curState != null ? curState.getClass().getSimpleName() : "null";
			Global.logger.info(owner + " [" + old_log + "]to[" + state.getClass().getSimpleName() + "]");
		}
		this.curState = state;
		this.curState.enter(this.owner);
	}

	public void toLastState() {
		if (lastState == null) {
			return;
		}
		this.changeState(this.lastState);
	}

	public void toNextState() {
		this.curState.toNextState(this.owner);
	}

	/**
	 * 执行服务器内部事件
	 * @param cmd
	 * @param gid
	 * @param param
	 */
	public void execute(String cmd, int gid, Object param) {
		this.curState.execute(this.owner, cmd, gid, param);
	}

}
