import { v4 } from 'uuid'
import { WSMessageHandler, WSServiceBase } from './PushMsgDeclare';

/**
* WebSocket 服务客户端
*/
export class PushMsgWsClient extends WSServiceBase { 
/**
 * 设置消息处理器
 * @param messageHandler 消息处理器
 */
useMessageHandler(messageHandler: WSMessageHandler):PushMsgWsClient {
    this.messageHandler = messageHandler
    return this;
}
/**
 * 创建WebSocket连接
 * @param wsUrl WebsocketURL ws://127.0.0.1/ wss://127.0.0.1/
 * @param context 上下文信息 {recordId:xxxx,userId:xxxx}
 */
async connectWS(wsUrl:string,context: any = {}): Promise<any>{
    if(!this.messageHandler) throw new Error('未实现 WSMessageHandler');
    this.context = context || {};
    this.sessionId = v4();
    this.ws = new WebSocket(this.processWsUrl(wsUrl));
    const that = this;
    this.ws.onopen = async (event) => { await that.onopen(event)};
    this.ws.onmessage = async (event) => { await that.onmessage(event)}
    this.ws.onclose = async (event) => { await that.onclose(event)}
}

private processWsUrl(wsUrl:string): string{
    let url = wsUrl
    if (!url.endsWith('/')) {
        url += '/'
    }
    url += 'cn.keytop.ns.api.76736.pushmsg/1.0.0'; 
    const params = 'sessionId=' + this.sessionId + '&' + Object.entries(this.context).map(([key, val]) => `${key}=${val }`).join('&');
    if (url.indexOf('?') > -1) {
        return url + '&' + params
    }else{
        return url + '?' + params
    }
}

} 
export { WSMessageHandler as PushMsgWSMessageHandler };
