import {expect} from "chai"
import {WebConnect} from "../../../source/net/webconnect.mjs";
import {Message} from "../../../source/net/webconnect/message.mjs";
import {Observer} from "../../../source/types/observer.mjs";
import {initWebSocket} from "../../util/websocket.mjs";

const testUrl = "wss://ws.postman-echo.com/raw"

describe('Websocket', function () {

    let ds = undefined

    before(function (done) {
        initWebSocket().then(() => {
            done()
        }).catch((e) => {
            done(e)
        })
    });

    afterEach(function (done) {
        if (ds) {
            ds.close()
        }

        // without this, the node test will hang 
        for (const sym of Object.getOwnPropertySymbols(ds)) {
            if (sym.toString() === 'Symbol(connection)') {
                if (typeof ds[sym]?.socket?.terminate === 'function') {
                    ds[sym]?.socket?.['terminate']()
                }
            }
        }

        done()
    });


    it('should transform data', function (done) {

        ds = new WebConnect( {
            url: testUrl,
        })

        ds.connect().then(() => {
            
            ds.attachObserver(new Observer(()=> {
               done()
            }))
            
            ds.send({
                data: {
                    message: "Hello World"
                }
            })

        }).catch((e) => {
            done(e)
        })


    })

    it('should connect', function (done) {
        ds = new WebConnect({
            url: testUrl,
            reconnect: {
                enabled: false
            }
        });
        ds.connect().then(() => {
            done()
        }).catch((e) => {
            done(e)
        })


    })

    it('should send message', function (done) {
        ds = new WebConnect({
            url: testUrl,
            reconnect: {
                enabled: false
            }
        });
        ds.connect().then(() => {

            ds.attachObserver(new Observer(()=> {
                
                expect(ds.dataReceived()).to.be.true
                
                try {
                    const msg = ds.poll()
                    expect(msg).to.be.instanceOf(Message)
                    const data = msg.getData()
                    expect(data).to.be.deep.equal({message: "Hello World"})
                } catch (e) {
                    done(e)
                    return
                }
                done()
            }))

            ds.send({
                    message: "Hello World"
            })

        }).catch((e) => {
            done(e)
        })


    }).timeout(10000);

});
