import assert from 'node:assert';


// this code is used in migrations - 20201120212726-apps-add-containerIp.js
function intFromIp(address) {
    assert.strictEqual(typeof address, 'string');

    const parts = address.split('.');

    if (parts.length !== 4) return null;

    return (parseInt(parts[0], 10) << (8*3)) & 0xFF000000 |
           (parseInt(parts[1], 10) << (8*2)) & 0x00FF0000 |
           (parseInt(parts[2], 10) << (8*1)) & 0x0000FF00 |
           (parseInt(parts[3], 10) << (8*0)) & 0x000000FF;
}

// this code is used in migrations - 20201120212726-apps-add-containerIp.js
function ipFromInt(input) {
    assert.strictEqual(typeof input, 'number');

    const output = [];

    for (let i = 3; i >= 0; --i) {
        const octet = (input >> (i*8)) & 0x000000FF;
        output.push(octet);
    }

    return output.join('.');
}

export default {
    ipFromInt,
    intFromIp
};
