'use strict';

const cluster = require('cluster');
const path = require('path');
const StalkedId = require('./models/stalked_id');


module.exports = function(server) {
    const io = require('socket.io')(server);
    const workers = {}; // {stalked_id: worker_id}

    io.on('connection', (socket) => {
        const username = socket.request.user._doc.username;
        socket.emit('connection', {message: 'Connection established.'});
        socket.on('join-room', join);

        socket.on('stalk-start', stalked_id => {
            // console.log(`Stalk request from ${username}, target: ${stalked_id}`);
            StalkedId.findOne({sid: stalked_id}).then(sid_data => {
                if (sid_data.subscribers.indexOf(username) === -1) {
                    sid_data.subscribers.push(username);
                    StalkedId.update({_id: sid_data._id}, {$set: {subscribers: sid_data.subscribers}}, () => {
                        join(stalked_id);
                    });
                }
            });
        });

        // socket.on('disconnect', () => {
        //     Object.keys(cluster.workers).forEach(id => cluster.workers[id].kill());
        // });

        socket.on('stalk-stop', stalked_id => {
            // console.log(io.nsps['/'].adapter.rooms);
            // console.log(socket.rooms);
            const room = io.nsps['/'].adapter.rooms[stalked_id];

            debugger
            // const worker_id = workers[stalked_id];
            // cluster.workers[worker_id].kill();
            // socket.disconnect();
        });

        function join(room) {
            const stalked_id = room;

            socket.emit('stalk-data', {stalked_id: stalked_id, message:'Connecting...'});
            StalkedId.findOneAndUpdate({sid: stalked_id}, {}, {upsert: true, new: true, setDefaultsOnInsert: true }).then(sid_data => {
                if (sid_data.subscribers.indexOf(username) !== -1) {
                    console.log(`Joining room ${room}`);
                    socket.join(room, err => {
                        if (err) {
                            console.log(err);
                        }
                    });
                    const worker_id = workers[stalked_id];
                    let worker = cluster.workers[worker_id];
                    if (!worker) {
                        console.log('Creating new WORKER.');
                        cluster.setupMaster({
                            exec: path.resolve(__dirname, '../vkstalk'),
                            args: ['stalk', stalked_id],
                            silent: true
                        });

                        worker = cluster.fork();
                        workers[stalked_id] = worker.id;
                        worker.process.stdout.on('data', buffer => {
                            io.sockets.to(room).emit('stalk-data', {stalked_id: stalked_id, message: buffer.toString('utf8')});
                        });
                    } else {
                        io.sockets.to(room).emit('stalk-data', {stalked_id: stalked_id, message:'Connected. Waiting for a message...'});
                    }
                } else {
                    socket.emit('stalk-data', {stalked_id: stalked_id, message: 'Stalker offline. Click "STALK" to turn it on.'});
                }
            });
        }
    });

    return io;
};

@@ -1203,358 +1203,13 @@
 p', 
-stalked_id =%3E %7B%0A            // console.log(io.nsps%5B'/'%5D.adapter.rooms);%0A            // console.log(socket.rooms);%0A            const room = io.nsps%5B'/'%5D.adapter.rooms%5Bstalked_id%5D;%0A%0A            debugger%0A            // const worker_id = workers%5Bstalked_id%5D;%0A            // cluster.workers%5Bworker_id%5D.kill();%0A            // socket.disconnect();%0A        %7D
+leave
 );%0A%0A
@@ -1608,9 +1608,24 @@
 og(%60
-J
+$%7Busername%7D is j
 oini
@@ -2968,32 +2968,32 @@
               %7D%0A
-
             %7D);%0A
@@ -2997,24 +2997,1559 @@
 );%0A        %7D
+%0A%0A        function leave(room) %7B%0A            const stalked_id = room;%0A            socket.emit('stalk-data', %7Bstalked_id: stalked_id, message:'Disconnecting...'%7D);%0A%0A            StalkedId.findOne(%7Bsid: stalked_id%7D).then(sid_data =%3E %7B%0A                const index = sid_data.subscribers.indexOf(username);%0A                if (index === -1) %7B%0A                    console.error(%60Username $%7Busername%7D is not subscribed to updates from $%7Bstalked_id%7D%60);%0A                    return;%0A                %7D%0A%0A%0A                sid_data.subscribers.splice(index, 1);%0A                StalkedId.update(%7B_id: sid_data._id%7D, %7B$set: %7Bsubscribers: sid_data.subscribers%7D%7D).then(() =%3E %7B%0A                    console.log(%60$%7Busername%7D is leaving room $%7Broom%7D%60);%0A                    socket.leave(room, err =%3E %7B%0A                        if (err) %7B%0A                            console.log(err);%0A                        %7D%0A                    %7D);%0A%0A                    socket.emit('stalk-data', %7Bstalked_id: stalked_id, message: 'Stalker offline. Click %22STALK%22 to turn it on.'%7D);%0A%0A                    if (!sid_data.subscribers.length) %7B%0A                        killStalker(stalked_id);%0A                    %7D%0A                %7D);%0A            %7D);%0A        %7D%0A%0A        function killStalker(stalked_id) %7B%0A            const worker_id = workers%5Bstalked_id%5D;%0A            if (!worker_id) %7B%0A                console.error(%60Worker (ID=$%7Bworker_id%7D) stalking $%7Bstalked_id%7D does not exist.%60);%0A                return;%0A            %7D%0A%0A            cluster.workers%5Bworker_id%5D.kill();%0A        %7D
 %0A    %7D);%0A%0A  

Allow web users to stop the stalker.