const MessagingAgent = require('./gameserver-messaging-agent-scratch');
const GameServerConnection = require('./gameserver-websocket-connection');

const query = window.location.search
    .replace('?', '')
    .split('&')
    .reduce((acc, str) => {
        const [key, val] = str.split('=');
        acc[key] = decodeURIComponent(val);
        return acc;
    }, {});
const hostname = query.hostname || window.location.hostname || 'localhost';
const id = query.id ? `?id=${query.id}` : '';
const address = `ws://${hostname}:7000/game${id}`;

/*
Note: Scratch MessagingAgent listens on variable changes,
other implementations must call messagingAgent.update() periodically
*/

module.exports = function GameServerClient (runtime) {
    const messagingAgent = new MessagingAgent({
        runtime
    });

    return new GameServerConnection({
        address,
        reconnectTimer: 5000,
        agent: messagingAgent
    });
};

/*
Note: Scratch MessagingAgent listens on variable changes,
other implementations must call messagingAgent.update() periodically
*/
