package ink.wgink.module.instantmessage.service.impl;

import ink.wgink.common.base.DefaultBaseService;
import ink.wgink.module.instantmessage.service.IWebSocketClientService;
import ink.wgink.module.instantmessage.websocket.manager.WebSocketChannelManager;
import ink.wgink.pojo.app.AppTokenUser;
import ink.wgink.util.UUIDUtil;
import org.springframework.stereotype.Service;

/**
 * @ClassName: WebSocketClientServiceImpl
 * @Description: webSocketk客户端
 * @Author: wanggeng
 * @Date: 2021/9/12 4:44 下午
 * @Version: 1.0
 */
@Service
public class WebSocketClientServiceImpl extends DefaultBaseService implements IWebSocketClientService {

    @Override
    public String login(String clientName) {
        String userId = securityComponent.getCurrentUser().getUserId();
        return initSession(userId, clientName);
    }

    @Override
    public String login(String token, String clientName) {
        AppTokenUser appTokenUser = getAppTokenUser(token);
        return initSession(appTokenUser.getId(), clientName);
    }

    /**
     * 初始化Socket会话
     *
     * @param userId     用户ID
     * @param clientName 客户端名称
     * @return
     */
    private synchronized String initSession(String userId, String clientName) {
        String sessionId = UUIDUtil.getUUID();
        // 通知下线
        WebSocketChannelManager.getInstance().logout(userId, clientName);
        System.out.println(">>>>>>>> sessionId: " + sessionId);
        WebSocketChannelManager.getInstance().init(userId, sessionId, clientName);
        return sessionId;
    }


}
