package com.group;


import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.data.cache.AccountCache;
import com.data.cache.GroupCache;
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 com.taurus.permanent.TPServer;
//import hunan.DoTest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import taurus.client.NetManager;


import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;

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";
	
	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("开始创建机器人连接...");
		//0 加载机器人到redis 2
		loadGroupRobot();

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



		// 2. 定时器只负责创建机器人连接
		TPServer.me().getTimerPool().scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				try {
					System.out.println("开始创建机器人连接1111111");
//					QingChu qingChu = new QingChu();
//					qingChu.qingchu();

					//发送 机器人加入房间
					
					//DoTest doTe = new DoTest();
					//doTe.doTest();

//					System.out.println("机器人返回结果: " + s);
				} catch (Exception e) {
//					System.out.println("创建机器人连接失败" + e);
				}
			}
		}, 0, 20 ,TimeUnit.SECONDS);
	}

	// 独立的事件处理线程
	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(){
		Jedis jedis2 = Redis.use("group1_db2").getJedis();
        try {
			String sql = String.format("SELECT id,acc,nick,portrait,password FROM `account` WHERE jiqiren=9998 and start = 0");
            ITArray robotIds = DataBase.use().executeQueryByTArray(sql);
			HashMap<String, String> robotMap = new HashMap<>();

			//遍历机器人，
			for(int i = 0; i < robotIds.size(); ++i) {
//				//把机器人按group 分类好 存放到redis2

				ITObject robot = robotIds.getTObject(i);
				Integer robotId = robot.getInt("id");
				String robotAcc = robot.getString("acc");
				String robotNick = robot.getString("nick");
				String robotPortrait = robot.getString("portrait");
				String robotPassword = robot.getString("password");

				robotMap.put("acc", robotAcc);
				robotMap.put("nick", robotNick);
				robotMap.put("portrait", robotPortrait);
				robotMap.put("password", robotPassword);
				jedis2.hmset("{robot}:" + robotId , robotMap);

//					String sqls = String.format("UPDATE `account` SET start = %d WHERE id = %d", 1, robotId);
//					DataBase.use().executeUpdate(sqls);
			}


			Map<String,String> gRobotMap = new HashMap<>();
			gRobotMap.put("start", "0");
			gRobotMap.put("pid", "66");
			jedis2.hmset("{Grobot}:"+101666, gRobotMap);



		} catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
			jedis2.close();
		}

    }

	@Override
	public void configRoute(Routes me) {

	}

	
	@Override
	public void onStop() {
		if(timeScheduler!=null) {
			timeScheduler.shutdownNow();
		}
	}


}
