package com.collabnet.ctf.events;

import com.vasoftware.sf.common.logger.Logger;
import com.vasoftware.sf.events.EventHandler60;

import java.io.File;

public class AsynchronousHookScriptEventListener extends EventHandler60 {

    private static final Logger log = Logger.getLogger(AsynchronousHookScriptEventListener.class);

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

    /**
     * Process Event
     *
     * @throws Exception
     */
    @Override
    public void processEvent() throws Exception {

        File hookScript = HookUtil.getHookScript(hookDirectory, getEventContext().getType(),
                getEventContext().getOperation());
        log.info("Going to call " + hookScript.getAbsolutePath() + " if it does exist.");
        if (hookScript.exists()) {

            log.info("Calling " + hookScript.getAbsolutePath());

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

            HookUtil.setEventContextInformationInEnvironment(getEventContext(), process);

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

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