/*
 * Licensed Materials - Property of IBM Corp.
 * IBM UrbanCode Deploy
 * (c) Copyright IBM Corporation 2017. All Rights Reserved.
 *
 * U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
 * GSA ADP Schedule Contract with IBM Corp.
 */
package com.urbancode.air.plugin.automation;

import com.urbancode.air.*

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class AutomationBase {
    //**************************************************************************
    // CLASS
    //**************************************************************************

    //**************************************************************************
    // INSTANCE
    //**************************************************************************
    String serverUrl
    String username
    String password
    String domain
    String project
    String successfulExitStatus

    def workDir
    CommandHelper cmdHelper
    def cscriptExe = "cscript.exe"
    final def PLUGIN_HOME = System.getenv('PLUGIN_HOME')

    protected void init() {
        cmdHelper = new CommandHelper(workDir)
        cmdHelper.ignoreExitValue = true

        if (new File("C:\\Windows\\SysWOW64").exists()) {
            cscriptExe = "C:\\Windows\\SysWOW64\\cscript.exe"
        }
    }

    protected void runCommand(message, command) {
        int exitCode = cmdHelper.runCommand(message, command)
        int successCode = successfulExitStatus.toInteger()
        if (exitCode != successCode) {
            throw new ExitCodeException("Invalid exit code: " + exitCode + ". Expected exit code " + successCode)
        }
    }

    protected String runCommandWithOutput(message, command, timeout) {
        String output

        def getTestOutput = {
            it.out.close() // close stdin
            def out = new PrintStream(System.out, true)
            StringBuilder outputBuilder = new StringBuilder()
            Object lock = new Object()
            try {
                if(timeout) {
                    synchronized (lock) { // obtain lock's monitor
                        // Release the lock, but wait only timeout specified for notify
                        lock.wait(timeout)
                    }
                }
                it.waitForProcessOutput(outputBuilder, out)
                output = outputBuilder.toString()
            }
            finally {
                out.flush()
            }
        }

        int exitCode = cmdHelper.runCommand(message, command, getTestOutput)
        int successCode = successfulExitStatus.toInteger()

        // Fail without returning output when tests failed to run.
        if (exitCode != successCode) {
            throw new ExitCodeException("Invalid exit code: " + exitCode + ". Expected exit code " + successCode)
        }

        return output
    }
}