package me.zhengjie.modules.system.service;

import me.zhengjie.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.websocket.Session;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class WebSocketService {

    public static BusDeviceService myDeviceService;
    @Autowired private BusDeviceService deviceService;

    // 初始化
    @PostConstruct
    public void init() {
        if (null == myDeviceService) {
            myDeviceService = deviceService;
        }
    }

    // 存储设备号
    public static List<String> deviceList = new ArrayList<>();
    // 观看视频的用户
    public static Set<String> videoUser = new LinkedHashSet<>();

    // 存储连接的客户端
    public String channel;
    public Session session;
    public static final ConcurrentHashMap<String, WebSocketService> clients = new ConcurrentHashMap<>();

    public WebSocketService getSocket(String key) {
        if (!StringUtils.isEmpty(key)) {
            return clients.get(key);
        }
        for (WebSocketService socketServer : clients.values()) {
            if (socketServer.equals(this)) {
                return socketServer;
            }
        }
        return null;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        WebSocketService that = (WebSocketService) o;
        return Objects.equals(session, that.session) && Objects.equals(channel, that.channel);
    }
}