const WebSocket = require('ws');


const wss = new WebSocket.Server({
    port: 3000
})


function numberToBinary(num) {
    const unpadded = (num >>> 0).toString(2)
    return unpadded.padStart(Math.ceil(unpadded.length / 8) * 8, '0');
}

function mistery(bin1, bin2) {
    return bin1.split('').map((b1, idx) => {
        const b2 = bin2.split('')[idx]

        if (!(b1 === '0' && b2 === '0') && !(b1 === '1' && b2 === '1'))
            return "1"
        else
            return "0"
    }).join('')
}


function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min)
}

function bitShift(byte) {
    return `${byte[byte.length - 1]}${byte.substring(0, byte.length - 1)}`
}

wss.on('connection', ws => {


    let seed          = "010010010100011101000011010101000100011001111011011011110100110001100100010011010110001101000100011011110100111001100001010011000110010001111101"
    let veggieIndices = "001000000110110111111101000010110110111101100111110000000001110100110000110100001000011000010011110001000001100011110011010110111001000010001111"

    ws.on('message', evt => {
        const magic = mistery(seed, veggieIndices)
            .split('')
            .reduce(([first, ...rest], val) => 
                first && first.length < 2 
                    ? [[...first, val], ...rest] 
                    : [[val], ...(first === undefined ? [] : [first]), ...rest], [])

        seed = magic.flatMap(x => x.join('')).join('')
        veggieIndices = bitShift(veggieIndices)


        ws.send(JSON.stringify(magic.reverse()))
    })
})