import {Client,Message }from '@stomp/stompjs';

let client = null;
// let url = `wss://mediate.dev.trydotec.com/mediate/ws/websocket`;
let subscriptionMap = {};

const socketClass = {
    // 初始化
    initStomp(url, succ, err) {
        // console.log('----过来了')
        client = new Client({
            brokerURL: url,
            debug: function (str) {
                console.log(str);
            },
        });
        client.onConnect = succ;
        client.onStompError = err;
        client.activate();
    },
    // 关闭
    deactivate() {
        if (!client)return;
        client.deactivate();
        client = null;
        subscriptionMap = {};
    },
    // 推送
    publish(data) {
        // data
        // {
        //   destination: '/topic/video-room/{roomid}',
        //   body: 'Hello world',
        //   headers: { priority: '9' },
        // }
        // console.log(data, '---发起消息111')
        if (!client)return;
        // console.log(data, '---发起消息222')
        client.publish(data);
    },
    // 订阅
    subscription(url, callback) {
        // url: /topic/video-room/{roomid}
        // callback = function (message) {
        //   // called when the client receives a STOMP message from the server
        //   if (message.body) {
        //     alert('got message with body ' + message.body);
        //   } else {
        //     alert('got empty message');
        //   }
        // };
        if (!client)return;
        subscriptionMap[url]  = client.subscribe(url, callback);
    },
    // 取消订阅
    unsubscribe(url) {
        // url: /topic/video-room/{roomid}
        if (!client)return;
        if (url){
            const a =  subscriptionMap[url];
            if (a){
                a.unsubscribe();
                delete subscriptionMap[url]
            }
        }
    }
}


export default socketClass;