package com.sjyt.icom.asst.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.sjyt.icom.asst.common.model.room.ExtraInfo;
import com.sjyt.icom.asst.common.model.room.Room;
import com.sjyt.icom.asst.context.pools.MeetRoomPool;
import com.sjyt.icom.asst.context.pools.One2OneRoomPool;
import com.sjyt.icom.asst.service.IRoomManner;
import lombok.Data;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * <p>房间管理基类</p>
 *
 * @author renyanru
 * @version V1.0.0
 * @date 2022/6/13 13:10
 */
@Data
public abstract class BaseRoomManagerService<T> implements IRoomManner<T> {
    protected final SendMsgService sendMsgService;
    protected final One2OneRoomPool oneRoomPool;
    protected final MeetRoomPool meetRoomPool;
    /**
     * 房间id：房间
     */
    private final Map<String, Room> roomMap = new ConcurrentHashMap<>(16);

    /**
     * 是否超过限定人数
     *
     * @return r false 未超过 true 超过
     */
    public boolean isOverQuota(String rid) {
        Room room = roomMap.get(rid);
        int quota = room.getQuota();
        return  room.getExtraInfos().size()>quota;
    }


    /**
     * 当前是否占线
     *
     * @param uid 用户标识
     * @return r
     */
    public boolean isBusy(String uid) {
        Collection<Room> values = roomMap.values();
        List<String> result = new ArrayList<>();
        for (Room value : values) {
            for (ExtraInfo user : value.getExtraInfos()) {
                result.add(user.getUid());
            }
        }
        return !result.contains(uid);
    }


    /**
     * 通过房间号，获取房间
     *
     * @param rid 房间号
     * @return 房间
     */
    public Room getRoom(String rid) {
        if (ObjectUtil.isNotNull(rid)) {
            return roomMap.get(rid);
        }
        return null;
    }

    /**
     * 获取房间人数
     * @param rid 房间号
     * @param excludeUid 排除指定人
     * @return r
     */
    public List<String> getNumber(String rid,String excludeUid){
        Room room = roomMap.get(rid);
        return Optional.ofNullable(room).map(Room::getExtraInfos).orElse(new HashSet<>())
                .stream().map(ExtraInfo::getUid)
                .filter(uid -> !uid.equals(excludeUid)).collect(Collectors.toList());
    }

    /**
     * 获取ExtraInfo
     * @param rid 房间号
     * @param excludeUid 排除指定人
     * @return List<ExtraInfo>
     */
    public List<ExtraInfo> getExtraInfo(String rid,String excludeUid){
        Room room = roomMap.get(rid);
        return room.getExtraInfos().stream().filter(it-> ObjectUtil.notEqual(it.getUid(),excludeUid)).collect(Collectors.toList());
    }

    /**
     * 保存房间
     * @param room room
     */
    public void addRoom(Room room){
        roomMap.put(room.getRid(),room);
    }

}
