package com.sjyt.icom.asst.endpoint;

import cn.hutool.core.util.ObjectUtil;
import com.sjyt.icom.asst.common.model.room.AbsClient;
import com.sjyt.icom.asst.common.model.room.IcomClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.yeauty.pojo.Session;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>TODO</p>
 *
 * @author renyanru
 * @version V1.0.0
 * @date 2022/7/1 11:41
 */
@Slf4j
@Component
public class BeanResolvable {
    private final Map<String, AbsClient> clientMap = new ConcurrentHashMap<>(16);

    /**
     * 添加客户端
     *
     * @param uid    用户id
     * @param client 客户端
     */
    public void addSession(String uid, AbsClient client) {
        if (ObjectUtil.isAllNotEmpty(uid, client)) {
            clientMap.put(uid, client);
        }
    }

    /**
     * 删除客户端
     *
     * @param session 会话
     */
    public void removeSession(Session session) {
        Optional.ofNullable(session)
                .map(Session::id)
                .ifPresent(id -> {
                    clientMap.values().stream()
                            .filter(it -> ObjectUtil.equal(id, it.getClientId()))
                            .map(AbsClient::getUid)
                            .forEach(clientMap::remove);
                });
    }

    public IcomClient getClient(String uid) {
        return Optional.ofNullable(uid).map(it -> {
            final AbsClient absClient = clientMap.get(it);
            IcomClient icomClient = null;
            if (absClient instanceof IcomClient) {
                icomClient = (IcomClient) absClient;
            }
            return icomClient;
        }).orElse(null);
    }

    public Session getSession(String uid) {
        return Optional.ofNullable(getClient(uid)).map(AbsClient::getSession).orElseGet(() -> {
            log.error("用户已下线");
            return null;
        });
    }
}
