package com.inspur.websoket.client.util;

import com.inspur.thrid.IPBXService;
import com.inspur.websoket.client.PBXWebSocketClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.URISyntaxException;

@Slf4j
@Component
public class PBXWebSocketUtils {

    @Value("${pbx.ws.path:ws://{pbx_ip}:{http_port}/{api_path}/subscribe?access_token=}")
    private static String wsPath;

    @Autowired
    private static IPBXService ipbxService;

    private static PBXWebSocketClient client;

    public static PBXWebSocketClient webSocketClient() {
        try {
            // 获取token
            String accessToken = ipbxService.getAccessToken();
            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;
    }

    /**
     * 获取websocket客户端
     * @return
     */
    public static PBXWebSocketClient getWBClient() {
        if(null != client){
            return client;
        }
        return webSocketClient();
    }


    /**
     * 订阅事件
     */
    public void subscribe() {
        //(30011) 通话记录更新
        //(30012) 新通话记录
        //(30013) 呼叫转移

    }

}
