const WebSocket = require('ws');
const Redis = require('ioredis');


const wsServer = new WebSocket.Server({ port: 9000 });

const redis = new Redis({
    port: 6379,
    host: "redis",
    username: "default",
    password: process.env.REDIS_PASSWORD,
    db: 0,
});



wsServer.on('connection', onConnect);

function onConnect(wsClient) {
    console.log('New connection');

    wsClient.on('close', function() {
        console.log('Connection closed');
    });

    wsClient.on('message', function(message) {
        console.log(message);
        try {
            const jsonMessage = JSON.parse(message);
            switch (jsonMessage.action) {
                case 'ECHO':
                    wsClient.send(jsonMessage.data);
                    break;
                case 'PING':
                    setTimeout(function() {
                        wsClient.send('PONG');
                    }, 2000);
                    break;
                default:
                    console.log('Неизвестная команда');
                    break;
            }
        } catch (error) {
            console.log('Ошибка', error);
        }
    });

    redis.subscribe("actions", (err, count) => {
        if (err) console.error(err.message);
        console.log(`Subscribed to ${count} channels.`);
    });

    redis.on("message", function (channel, data) {
        wsClient.send(data);
        data = JSON.parse(data).data;
        console.log(`send new message to user ${data.user_id} in the channel '${channel}'.`);
    });

}


