package com.group;


import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.data.cache.AccountCache;
import com.data.cache.GroupCache;
import com.group.robot.RobotManager;
import com.group.robot.info.RobotInfo;
import com.taurus.core.entity.ITArray;
import com.taurus.core.entity.ITObject;
import com.taurus.core.plugin.database.DataBase;
import com.taurus.core.plugin.redis.Redis;
import com.taurus.core.routes.Extension;
import com.taurus.core.routes.Routes;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import taurus.client.NetManager;


public class MainServer extends Extension {
	private static final Logger log = LoggerFactory.getLogger(MainServer.class);
	private ScheduledThreadPoolExecutor timeScheduler;
	
	private static final String WEB_CONFIG_KEY = "web_config";
	private static final String FORCE_VER_KEY = "force_ver";
	
	//机器人管理器
	private RobotManager robotManager = new RobotManager();

	public static Map<String,String> lua_map = new HashMap<>();
	public MainServer() {
		super();
		//3秒
//		NetManager.TIMEOUT_TIME =3;
		System.out.println("MainServer");
		timeScheduler = new ScheduledThreadPoolExecutor(1);
		timeScheduler.scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				AccountCache.clearData();
				GroupCache.clearData();
				System.gc();
			}
		}, 0,600, TimeUnit.SECONDS);

	}

	@Override
	public int readVersion() {
		int ver = Integer.parseInt(Redis.use("group1_db1").hget(WEB_CONFIG_KEY,FORCE_VER_KEY));
		return ver;
	}



	@Override
	public void onStart() {
		System.out.println("开始创建机器人连接...");

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

		//2.加载机器人到redis 2
		loadGroupRobot();
		
		//关闭时重置机器人状态
		Runtime.getRuntime().addShutdownHook(new Thread(this::resetRobotStatus));
	}

	/**
	 * 重置机器人状态为未使用
	 */
	private void resetRobotStatus() {
		try {
			String sql = "UPDATE account SET start = 0 WHERE jiqiren = 9998";
			DataBase.use().executeUpdate(sql);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 独立的事件处理线程
	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();
	}

	/**
	 * 把机器人加载到redis2
	 */
	private void loadGroupRobot(){
		String sql = "SELECT id,acc,nick,portrait,password FROM `account` WHERE jiqiren=9998 and start = 0";
        ITArray robotIds = null;
        try {
            robotIds = DataBase.use().executeQueryByTArray(sql);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        Map<Integer, Integer> gameRobotConfig = new HashMap<>();
		gameRobotConfig.put(10, 10);
		gameRobotConfig.put(22, 0);
		int robotIndex = 0;

		//长沙麻将机器人
		List<RobotInfo> csRobots = new ArrayList<>();
		for (int i = 0; i < gameRobotConfig.get(10) && robotIndex < robotIds.size(); i++, robotIndex++) {
			ITObject robot = robotIds.getTObject(robotIndex);
			RobotInfo robotInfo = createRobotInfo(robot, 10);
			csRobots.add(robotInfo);
		}

		//红中麻将机器人
		List<RobotInfo> hzRobots = new ArrayList<>();
		for (int i = 0; i < gameRobotConfig.get(22) && robotIndex < robotIds.size(); i++, robotIndex++) {
			ITObject robot = robotIds.getTObject(robotIndex);
			RobotInfo robotInfo = createRobotInfo(robot, 22);
			hzRobots.add(robotInfo);
		}

		log.info("机器人分配完成：长沙麻将{}个，红中麻将{}个", csRobots.size(), hzRobots.size());

		//登录分配的机器人
		//初始化机器人管理器
		robotManager.loginRobots(csRobots, 10);
		robotManager.loginRobots(hzRobots, 22);
    }

	/**
	 * 创建机器人信息对象
	 */
	private RobotInfo createRobotInfo(ITObject robotObj, int wanfaId) {
		RobotInfo robot = new RobotInfo();
		robot.setRobotId(robotObj.getInt("id"));
		robot.setAccount(robotObj.getString("acc"));
		robot.setNickName(robotObj.getString("nick"));
		robot.setPortrait(robotObj.getString("portrait"));
		robot.setPassword(robotObj.getString("password"));
		robot.setWanfaId(wanfaId);
		return robot;
	}

	@Override
	public void configRoute(Routes me) {

	}

}