const devicePubSub = new DevicePubSub(onMessage);
var contentText;
var output;

devicePubSub.websocket.on('connection', () => {
    writeToScreen('<span>Connected</span>');
});
devicePubSub.websocket.on('disconnect', () => {
    writeToScreen(`<span style='color: red'>Disconnected</span>`);
});
devicePubSub.websocket.on('connect_error', err => {
    writeToScreen(`<span style='color: red'>Error: ${err.data}</span>`);
});

function init() {
    contentText = document.querySelector('#content-text');
    output = document.getElementById('output');
}

function onMessage(msg) {
    console.log(`msg: ${JSON.stringify(msg)}`);
    writeToScreen(`<span>Received: ${msg.data}</span>`);
    if (msg.data)
        contentText.innerHTML = (contentText.innerHTML === 'Service') ? 'D2D' : 'Service';
}

function writeToScreen(msg) {
    const pre = document.createElement('p');
    pre.style.wordWrap = 'break-word';
    pre.innerHTML = msg;
    output.appendChild(pre);
}

window.onload = function() {
    // TODO: Do your initialization job
    init();

    // Sample code
    const mainPage = document.querySelector('#main');
    mainPage.addEventListener('click', function() {
        writeToScreen('Sent: ' + contentText.innerHTML);
        devicePubSub.send('test', contentText.innerHTML);
    });
};
