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

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

function onMessage(msg) {
    console.log(`msg : ${JSON.stringify(msg)}`);
    if (msg.id == devicePubSub.SERVER && msg.type == 'new_client') {
        writeToScreen(`<span>New client: ${msg.data}</span>`);
    } else {
        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);
}

function sendToAll(msg) {
    writeToScreen('Sent: ' + msg);
    devicePubSub.send('test', msg);
}

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

    // add eventListener for tizenhwkey
    document.addEventListener('tizenhwkey', function(e) {
        if (e.keyName === 'back') {
            try {
                tizen.application.getCurrentApplication().exit();
            } catch (ignore) {}
        }
    });

    // Sample code
    const mainPage = document.querySelector('#main');
    mainPage.addEventListener('click', function() {
        sendToAll(contentText.innerHTML)
    });
};
