'use strict';

var service_ftm = new Subscription("FTM_CONTROL/FTU_LIST");

// Make sure that we receive a 'Yes, we are connected' event
service_ftm.get(5000);

// Wait for the format string to be available
// FIXME: Timeout
while (!dim.send("FTM_CONTROL"))
    v8.sleep();

// Check for all FTUs to be connected when the next event arrives
service_ftm.onchange = function(event)
{
    var ping = event.obj['Ping'];
    for (var i=0; i<40; i++)
    {
        if (ping[i]==1)
            continue;

        console.out("Problems in the FTU communication found.");
        console.out("Send command to disable all FTUs.");
        console.out(" => Power cycle needed.");

        dim.send("FTM_CONTOL/ENABLE_FTU", -1, false);
        throw new Error("CrateReset[FTU]");
    }

    // Signal success by closing the connection
    service_ftm.close();
}

// Send ping (request FTU status)
dim.send("FTM_CONTROL/PING");

// Wait for 1 second for the answer
var timeout = new Thread(1000, function(){ if (service_ftm.isOpen) throw new Error(""); });
while (service_ftm.isOpen)
    v8.sleep();

