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

import com.sjyt.icom.asst.common.model.message.News;
import com.sjyt.icom.asst.common.model.room.AbsClient;
import com.sjyt.icom.asst.common.model.room.AbsRoom;
import com.sjyt.icom.asst.context.handle.room.RoomFactory;
import com.sjyt.icom.asst.endpoint.BeanResolvable;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;

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

/**
 * <p>房间管理基类</p>
 *
 * @author renyanru
 * @version V1.0.0
 * @date 2022/6/13 13:10
 */
@AllArgsConstructor
public abstract class BaseRoomManagerService<T> {
    /**
     * 房间id：房间
     */
    protected final Map<String, AbsRoom> roomMap = new ConcurrentHashMap<>(16);

    private final RoomFactory roomFactory;

    private final BeanResolvable beanResolvable;

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

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


    /**
     * 通过房间号，获取房间
     *
     * @param rid 房间号
     * @return 房间
     */
    public AbsRoom getRoom(String rid) {
        return Optional.ofNullable(rid).map(roomMap::get).orElse(null);
    }

    /**
     * 保存房间
     *
     * @param absRoom absRoom
     */
    public void addRoom(AbsRoom absRoom) {
        Optional.ofNullable(absRoom).ifPresent(it->{
            roomMap.put(absRoom.getRid(), absRoom);
        });
    }

    /**
     * 获取房间工厂
     * @return roomFactory
     */
    public RoomFactory getRoomFactory() {
        return roomFactory;
    }

    public BeanResolvable getBeanResolvable() {
        return beanResolvable;
    }

    public void notice(AbsClient client, News news){
        final String uid = client.getUid();

    }
}
