import com.urbancode.air.plugin.wldeploy.WebLogicStatusHelper;
import com.urbancode.air.AirPluginTool;

final def workDir = new File('.').canonicalFile
def apTool = new AirPluginTool(this.args[0], this.args[1]);
def props = apTool.getStepProperties();
final def jmxUrl = props['jmxUrl'];
final def user = props['user'];
final def pass = props['password'];
def targets = props['targets'];
final def timeout = props['timeout'];

targets = targets.split(',');

try {
    WebLogicStatusHelper helper = new WebLogicStatusHelper();
    helper.initConn(jmxUrl, user, pass);
    targets.each { target ->
        System.out.println("Starting Target ${target}");
        helper.startManagedServer(target);
    }

    def badStatuses = [];
    badStatuses << "start";
    long startTime = System.currentTimeMillis();
    while (!badStatuses.isEmpty() && System.currentTimeMillis()-startTime<(timeout.toInteger())*1000) {
        Thread.sleep(10000);
        badStatuses.clear();
        targets.each { target ->
            System.out.println("Checking Target ${target}");
            def status = helper.getManagedServerStatus(target);
            if (status instanceof List) {
                status.each { serverStatusPair ->
                    println serverStatusPair;
                    if (serverStatusPair[1] != "RUNNING") {
                        badStatuses << [serverStatusPair[0], serverStatusPair[1]];
                    }
                }
            }
            else {
                println status;
                if (status != "RUNNING") {
                    badStatuses << [target, status];
                }
            }
        }
    }
    targets.each { target ->
        apTool.setOutputProperty("state-$target", helper.getManagedServerStatus(target));
    }
    apTool.storeOutputProperties();
    helper.closeConn();
}
catch (Exception e) {
    e.printStackTrace();
    throw e;
}