
var innovaphone = innovaphone || {};

innovaphone.ModelTest = innovaphone.ModelTest || function (start, model) {
    var that = this;
    var src;
    model.onupdate.attach(() => {
        if (model.connection.state == "CONNECTED") {
            if (src) src.close();
            src = new (model.getApp()).Src(op);
            src.send({ mt: "Monitor", type: "model" });
        }
    });

    function op(msg) {
        if (!msg?.info?.op) return;

        if (msg.info.op == "echo") {
            src.send({ mt: "MonitorNotify", type: "tester", info: { op: "echoReply" } });
        }
        else if (msg.info.op == "new") {
            if (!msg.info.obj) msg.info.obj = msg.info.function;
            that[msg.info.obj] = {};
            that[msg.info.obj].model = new model[msg.info.function]();
            if (msg.info.events) {
                that[msg.info.obj].events = [];
                for (let e of msg.info.events) {
                    console.log("event", e);
                    that[msg.info.obj].events.push(e);
                    that[msg.info.obj].model[e].attach(handler);
                }
            }
        }
        else if (msg.info.op == "call") {
            if (msg.info.static) model[msg.info.static][msg.info.function](...msg.info.args, (...args) => {
                src.send({ mt: "MonitorNotify", type: "tester", info: { op: "ondone", args: args } });
            });
            else if (msg.info.obj) that[msg.info.obj].model[msg.info.function](...msg.info.args, (...args) => {
                src.send({ mt: "MonitorNotify", type: "tester", info: { op: "ondone", args: args } });
            });
        }
    }

    function handler(sender, args) {
        src.send({ mt: "MonitorNotify", type: "tester", info: { op: "event", sender: sender, args: args } });
    }
}
