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

        let name = config.name;
        let TS_set = parseFloat(config.TS_set);
        const inlet_sludge = 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 C_in = msg.payload.C;
                    let F2 = (F_in * C_in[12]) / TS_set;

                    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;
                    msg_F1.payload.C[7] = 0;
                    msg_F1.payload.C[8] = 0;
                    msg_F1.payload.C[9] = 0;
                    msg_F1.payload.C[10] = 0;
                    msg_F1.payload.C[11] = 0;
                    msg_F1.payload.C[12] = 0;

                    let msg_F2 = {...msg};
                    msg_F2.payload.F = F2_corr;
                    if (F2_corr > 0) {
                        msg_F2.payload.C[7] = F_in * C_in[7] / F2;
                        msg_F2.payload.C[8] = F_in * C_in[8] / F2;
                        msg_F2.payload.C[9] = F_in * C_in[9] / F2;
                        msg_F2.payload.C[10] = F_in * C_in[10] / F2;
                        msg_F2.payload.C[11] = F_in * C_in[11] / F2;
                        msg_F2.payload.C[12] = F_in * C_in[12] / F2;
                    }
                    msg_F2.payload.inlet = inlet_sludge;

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

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

    }
    RED.nodes.registerType("settling-basin", settler);
};
