module.exports = function(RED) {
    function recirculation(config) {
        RED.nodes.createNode(this, config);
        var node = this;

        let name = config.name;
        let F2 = parseFloat(config.F2);
        const inlet_F2 = parseInt(config.inlet);

        node.on('input', function(msg, send, done) {
            switch (msg.topic) {
                case "Fluent":
                    // conserve volume flow debit
                    let F_in = msg.payload.F;
                    let F1 = Math.max(F_in - F2, 0);
                    let F2_corr = F_in < F2 ? F_in : F2;

                    let msg_F1 = structuredClone(msg);
                    msg_F1.payload.F = F1;

                    let msg_F2 = {...msg};
                    msg_F2.payload.F = F2_corr;
                    msg_F2.payload.inlet = inlet_F2;

                    send([msg_F1, msg_F2]);
                    break;
                case "clock":
                    break;
                default:
                    console.log("Unknown topic: " + msg.topic);
            }

            if (done) {
                done();
            }
        });

    }
    RED.nodes.registerType("recirculation-pump", recirculation);
};
