package com.collabnet.ctf.events;

import java.io.File;

@EventListener(version = SoapVersion.SOAP_60)
public class AsynchronousHookScriptEventListener {

    private static String hookDirectory = "/opt/collabnet/teamforge/hooks/asynchronous/";

    /**
     * Process Event
     *
     * @throws Exception
     */
    @Asynchronous(topic = "*.*", user = "system")
    public void executeHookScript(final EventContext context) throws Exception {

        File hookScript = HookUtil.getHookScript(hookDirectory, context.getEventTopic(),
                context.getEventOperation());
        context.logInfo("Going to call " + hookScript.getAbsolutePath() + " if it does exist.");
        if (hookScript.exists()) {

            context.logInfo("Calling " + hookScript.getAbsolutePath());

            ProcessBuilder process = new ProcessBuilder(hookScript.getAbsolutePath());

            HookUtil.setEventContextInformationInEnvironment(context, process);

            HookUtil.setResultValuesInEnvironment(process, context.getOriginalData(), "original");
            HookUtil.setResultValuesInEnvironment(process, context.getUpdatedData(), "updated");

            Process runningProcess = process.start();
            runningProcess.getOutputStream().close();
        }
    }
}
