package com.inspur.websoket.client.util;

import com.inspur.common.utils.spring.SpringUtils;
import com.inspur.thrid.IPBXService;
import com.inspur.websoket.client.PBXWebSocketClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

/**
 * @description: websocket工具类
 * @author lihao16
 */
@Slf4j
@Service
public class PBXWebSocketUtils {

    private static IPBXService ipbxService = SpringUtils.getBean(IPBXService.class);

    private static PBXWebSocketClient client;

    public static PBXWebSocketClient webSocketClient() {
        try {
            // 获取token
            String accessToken = ipbxService.getAccessToken();
            // String wsPath = InspurConfig.getWsPath();
            // String wsPath = "ws://192.168.1.151:80/openapi/v1.0/subscribe?access_token=";
            String wsPath = "ws://10.219.166.91:80/openapi/v1.0/subscribe?access_token=";
            PBXWebSocketClient webSocketClient = new PBXWebSocketClient(new URI(wsPath + accessToken));
            webSocketClient.connect();
            client = webSocketClient;
            return webSocketClient;
        } catch (URISyntaxException e) {
            e.printStackTrace();
            log.error("创建websocket连接出现异常!", e);
        }
        return null;
    }

    @Bean
    public static PBXWebSocketClient getWBClient() throws NoSuchAlgorithmException, KeyManagementException {
        if(null != client){
            return client;
        }
        return webSocketClient();
    }

    /**
     * 心跳保持
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public static void wsHeartbeat() throws NoSuchAlgorithmException, KeyManagementException {
        if (null == client) {
            webSocketClient();
        }
        String heartbeat = "heartbeat";
        client.send(heartbeat);
        log.info("发送心跳包:{}", heartbeat);
    }


}
