package com.mgr.group.data;

import java.util.Map.Entry;
import java.util.Set;

import com.data.bean.BaseBean;
import com.data.cache.BaseCache;
import com.data.cache.GroupCache;
import com.taurus.core.entity.ITArray;
import com.taurus.core.entity.ITObject;
import com.taurus.core.entity.TArray;
import com.taurus.core.entity.TObject;
import com.taurus.core.plugin.redis.Redis;
import com.taurus.core.util.Utils;

import redis.clients.jedis.Jedis;

public class RoomCache extends BaseCache{
	private int groupId;
	private long last_time;
	private ITArray rooms;
	
	protected RoomCache(int groupId) {
		super("room:","group1_db0");
		this.groupId = groupId;
		this.fillSize = 6;
		this.readTime = 1;
		rooms = TArray.newInstance();
	}
	
	@Override
	protected BaseBean newBean() {
		return new Room();
	}
	
	public final void updateRoom() {
		rooms.clear();
		Set<Entry<Integer, BaseBean>> set = this.mapById.entrySet();
		for(Entry<Integer, BaseBean> entry : set) {
			Room gp =(Room)entry.getValue();
			if(!gp.del) {
				rooms.addTObject(gp.data);
			}else {
				this.mapById.remove(gp.id);
				this.mapByKey.remove(gp.redis_key);
			}
		}
	}
	
	/**
	 * 获取房间列表
	 * @return
	 */
	public final ITArray getRoomList(){
		if(System.currentTimeMillis() - last_time < 10000) {
			ITArray arr = TArray.newInstance();
			Utils.arrayCopy(rooms, arr);
			return arr;
		}
		
		rooms.clear();
		last_time = System.currentTimeMillis();
		String grooms_key = GroupCache.genRoomsKey(groupId);
		Jedis jedis11 = Redis.use("group1_db11").getJedis();
		Set<String> rooms = jedis11.zrangeByScore(grooms_key, 100000, 2000000);
		try {
			for (String tem : rooms) {
				Room room = this.getBean(tem);
				if(room==null) {
					jedis11.zrem(grooms_key, tem);
					continue;
				}
				room.del = false;
				jedis11.zadd(grooms_key, room.priorityValue, tem);
				this.rooms.addTObject(room.data);
			}
			jedis11.zremrangeByScore(grooms_key, 0, 0);
		}finally {
			jedis11.close();
		}
		
		ITArray arr = TArray.newInstance();
		Utils.arrayCopy(this.rooms, arr);
		return arr;
	}

}
