package robot.mj;

import java.util.Map;

import com.robot.GameController;
import com.robot.MainServer;
import com.robot.data.Player;
import com.robot.data.Room;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import taurus.client.NetManager;

import java.util.concurrent.TimeUnit;

/**
 * 长沙麻将机器人主服务器
 * TCP服务端接收robot_mgr的协议 同时作为客户端连接game_mj_cs处理AI逻辑
 */
public class EXMainServer extends MainServer{
	private static final Logger log = LoggerFactory.getLogger(EXMainServer.class);

	@Override
	public void onStart() {
		super.onStart();

		// 1. 先启动独立的事件处理线程（只启动一次）
		startNetEventThread();

		//5、干活
		log.info("长沙麻将机器人服务器已启动");
		log.info("服务器将监听端口 {} 用于接收robot_mgr管理协议", gameSetting.port);
	}

	/**
	 * 独立的事件处理线程
	 */
	private void startNetEventThread() {
		Thread eventThread = new Thread(() -> {
			while (true) {
				NetManager.processEvents();
				try {
					Thread.sleep(2);
				} catch (InterruptedException e) {
					break;
				} catch (Exception e) {
				}
			}
		}, "NetEvent-Thread");

		eventThread.setDaemon(true); // 设置为守护线程
		eventThread.start();
	}



	@Override
	public Room newRoom(String roomid, Map<String, String> redis_room_map) {
		return new EXRoom(roomid, redis_room_map);
	}

	@Override
	public Player newPlayer(int i, Room room, String s) {
		return new EXPlayer(i, room, s);
	}


	protected GameController newController() {
		return new EXGameController();
	}

	@Override
	public void onStop() {
		super.onStop();

		log.info("长沙麻将机器人服务器已停止");
	}
}