import {global} from 'http://devtalk.kospo.co.kr:3000/static/js/module/variable.js';
import {talkEvent} from 'http://devtalk.kospo.co.kr:3000/static/js/module/talkEvent.js';
import Common from "http://devtalk.kospo.co.kr:3000/static/js/utils.js";

class SocketQueue {
    constructor() {
        this.queue = [];
        this.isSending = false;
    }

    enqueue(data) {
        this.queue.push(data);
        if(!this.isSending) {
            this.processQueue();
        }
    }

    async processQueue() {
        this.isSending = true;
        while(this.queue.length > 0) {
            const data = this.queue.shift();
            try {
                await this.sendToSocket(data);
                Common.sleep(30).then(() => {
                    this.isSending = false;
                });
            } catch(err) {
                this.isSending = false;
                console.error('전송실패', err)
            }
        }
    }

    async sendToSocket(data) {
        return new Promise((resolve, reject) => {
            if(global.sockJS.readyState === WebSocket.OPEN) {
                talkEvent.send(global.talkParams(data));
                resolve();
            } else {
                reject(new Error('소켓 연결 안됨'))
            }
        })
    }
}

export default SocketQueue