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 com.taurus.core.plugin.redis.Redis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import robot.mj.info.RobotUser;
import taurus.client.NetManager;

import static robot.mj.EXGameController.robotRoomMapping;

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

	private static final RobotConnectionManager robotConnectionManager = new RobotConnectionManager();

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

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

		// 2. 启动连接检查定时任务
		//startConnectionCheckScheduler();
		//测试
		Jedis jedis2 = Redis.use("group1_db2").getJedis();
		String robotskey = "g{"+Config.DEFAULT_GROUP_ID+"}:play:"+ Config.DEFAULT_PID;
		Map<String, String> maprobot =	jedis2.hgetAll(robotskey);
		for(Map.Entry<String, String> entry : maprobot.entrySet()) {
			System.out.println(entry.getKey() + ":" + entry.getValue());
			//是否创建
			RobotUser robotUser = new RobotUser();
			robotUser.setRobotId(entry.getKey());
			robotUser.setPassword(Config.DEFAULT_PASSWORD);
			robotUser.setGameHost(Config.GAME_SERVER_HOST);
			robotUser.setGamePort(Config.GAME_SERVER_PORT);
			robotUser.setRobotGroupid(Config.DEFAULT_GROUP_ID);
			robotUser.setRobotPid(Config.DEFAULT_PID);

			robotRoomMapping.put(entry.getKey(), robotUser);
		}

		for(Map.Entry<String, RobotUser> entry : robotRoomMapping.entrySet()) {
			RobotUser robotUser = entry.getValue();
			//1、登录
			//判断是否登录
			if(!robotUser.isLogin){
				robotConnectionManager.login(robotUser);
			}
		}

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

		jedis2.close();
	}

	/**
	 * 独立的事件处理线程
	 */
	private void startNetEventThread() {
		Thread eventThread = new Thread(() -> {
			while (true) {
				NetManager.processEvents();
				try {
					Thread.sleep(2);
				} catch (InterruptedException e) {
					break;
				} catch (Exception e) {
				}
			}
		}, "paodekuai-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("跑得快机器人服务器已停止");
	}
}