package com.xydl.cac.socket;

import com.xydl.cac.model.MessageModel;
import com.xydl.cac.util.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;

@ServerEndpoint(value = "/websocket")
@Component
@Slf4j
public class WebSocketServer {

    private static List<Session> sessionPools = new ArrayList<>();

    @OnOpen
    public void onOpen(Session session) {
        sessionPools.add(session);
        log.info("当前socket连接数" + sessionPools.size());
    }

    @OnClose
    public void onClose(Session session) {
        sessionPools.remove(session);
        log.info("剩余socket连接数" + sessionPools.size());
    }

    public void sendMessage(String message, Integer warningId) {
        MessageModel msg = new MessageModel();
        msg.setType(1);
        msg.setContent(message);
        msg.setWarningId(warningId);
        String json = JSONUtil.object2Json(msg);
        Iterator<Session> it = sessionPools.listIterator();
        while (it.hasNext()) {
            Session session = it.next();
            try {
                session.getBasicRemote().sendText(json);
            } catch (Exception ignore) {
            }
        }
    }

    //收到客户端信息
    @OnMessage
    public void onMessage(Session session, String message) {
        try {
            if (!"1".equals(message)) {
                message = message.replaceAll("吗", "")
                        .replaceAll("b", "c")
                        .replaceAll("a", "b")
                        .replaceAll("你", "我")
                        .replaceAll("？", "!")
                        .replaceAll("\\?", "!");
                session.getBasicRemote().sendText(message);
            }
        } catch (IOException ignore) {
        }
    }

    //错误时调用
    @OnError
    public void onError(Session session, Throwable e) {
        sessionPools.remove(session);
        log.info("剩余socket连接数" + sessionPools.size());
    }

}
