package com.group;


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.group.controller.GroupController;
import com.group.controller.GroupLogController;
import com.group.controller.GroupRoomController;
import com.group.job.UpdatePlayRoomJob;
import com.group.job.UpdateRobotRoomJob;
import com.taurus.core.plugin.redis.Redis;
import com.taurus.core.routes.Extension;
import com.taurus.core.routes.Routes;
import com.taurus.core.util.FileUtil;


import org.quartz.CronTrigger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;


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

public class MainServer extends Extension {
	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();
	}

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


	@Override
	public void configRoute(Routes me) {
		me.setInterceptor(new WebInterceptor());

		me.add("group", GroupController.class);
		me.add("group/room", GroupRoomController.class);
		me.add("group/log",GroupLogController.class);
	}


	public void initJob() {

		try {
			SchedulerFactory sf = new StdSchedulerFactory();

			Scheduler schedrobot = sf.getScheduler();
			JobDetail robot = newJob(UpdateRobotRoomJob.class).withIdentity("update_robot_room", "group").build();
			CronTrigger robottg= newTrigger().withIdentity("update_robot_room_trigger", "group").withSchedule(cronSchedule("0/4 * * * * ? ")).build();
			schedrobot.scheduleJob(robot, robottg);


			robot = newJob(UpdateRobotRoomJob.class).withIdentity("create_robot_room", "group").build();
			robottg= newTrigger().withIdentity("create_robot_room_trigger", "group").withSchedule(cronSchedule("0/3 * * * * ? ")).build();
			schedrobot.scheduleJob(robot, robottg);
			schedrobot.start();

		}
		catch(Exception e) {

		}
	}

	@Override
	public void onStart() {
		/*JedisPoolConfig poolConfig = new JedisPoolConfig();
		poolConfig.setMaxTotal(100);      // 最大连接数
		poolConfig.setMaxIdle(50);        // 最大空闲连接数
		poolConfig.setMinIdle(10);        // 最小空闲连接数

		// 连接等待配置
		poolConfig.setMaxWaitMillis(3000); // 获取连接最大等待时间（毫秒）
		poolConfig.setBlockWhenExhausted(true); // 连接耗尽时是否阻塞

		// 连接验证配置
		poolConfig.setTestOnBorrow(true);    // 获取连接时验证
		poolConfig.setTestOnReturn(false);   // 归还连接时验证
		poolConfig.setTestWhileIdle(true);   // 空闲时验证

		// 空闲连接清理配置
		poolConfig.setMinEvictableIdleTimeMillis(60000);    // 最小空闲时间
		poolConfig.setTimeBetweenEvictionRunsMillis(30000); // 检查间隔
		poolConfig.setNumTestsPerEvictionRun(-1);

		JedisPool jedisPool = new JedisPool(poolConfig,"r-2vc0x3clldkj94synhpd.redis.cn-chengdu.rds.aliyuncs.com",6379,2000,"KuaiLjzhu@2026");


		cleanIdleConnectionsByBorrowAndReturn(jedisPool);*/
		// 1. 先启动独立的事件处理线程（只启动一次）
		Thread eventThread = new Thread(() -> {
			while (true) {
				try {
					UpdateRobotRoomJob urj = new UpdateRobotRoomJob();
					urj.createRobotRoom();
					//urj.updateRobotRoom();
					Thread.sleep(5000);

				} catch (InterruptedException e) {
					break;
				} catch (Exception e) {
				}
			}
		}, "Web_Group_Robot-Thread");

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


		Thread eventThread2 = new Thread(() -> {
			while (true) {
				try {
					UpdateRobotRoomJob urj = new UpdateRobotRoomJob();
					//urj.createRobotRoom();
					urj.updateRobotRoom();
					Thread.sleep(4000);

				} catch (InterruptedException e) {
					break;
				} catch (Exception e) {
				}
			}
		}, "Web_Update_Group_Robot-Thread");

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

	}

	public static void cleanIdleConnectionsByBorrowAndReturn(JedisPool jedisPool) {
		System.out.println("=== 开始手动清理空闲连接 ===");

		int initialIdle = jedisPool.getNumIdle();
		int initialActive = jedisPool.getNumActive();
		System.out.printf("清理前 - 空闲: %d, 活跃: %d%n", initialIdle, initialActive);

		// 获取当前空闲连接数
		int idleConnections = initialIdle;

		// 如果空闲连接超过阈值，开始清理
		if (idleConnections > 20) {
			int connectionsToClean = idleConnections - 10; // 保留10个空闲连接

			System.out.printf("需要清理 %d 个空闲连接%n", connectionsToClean);

			for (int i = 0; i < connectionsToClean; i++) {
				try (Jedis jedis = jedisPool.getResource()) {
					// 验证连接是否有效
					String pong = jedis.ping();
					if (!"PONG".equals(pong)) {
						System.out.printf("连接 %d 无效，将被销毁%n", i + 1);
					}
					// 获取后立即关闭，如果连接空闲时间过长，连接池会自动销毁
				} catch (Exception e) {
					System.err.printf("处理连接 %d 时出错: %s%n", i + 1, e.getMessage());
				}

				// 小延迟，避免对Redis造成压力
				try {
					TimeUnit.MILLISECONDS.sleep(10);
				} catch (InterruptedException e) {
					Thread.currentThread().interrupt();
				}
			}
		}

		int finalIdle = jedisPool.getNumIdle();
		int finalActive = jedisPool.getNumActive();
		System.out.printf("清理后 - 空闲: %d, 活跃: %d%n", finalIdle, finalActive);
		System.out.printf("共清理了 %d 个空闲连接%n", initialIdle - finalIdle);
		System.out.println("=== 手动清理完成 ===\n");
	}


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




}
