/*******************************************************************************
* Copyright (c)                                                                *
*           2005   Tristan Allwood,                                            *
*           2005   Daniel Burke,                                               *
*           2005   Marc Hull,                                                  *
*           2005   Ekaterina Itskova,                                          *
*           2005   Steve Zymler                                                *
*                                                                              *
* Permission is hereby granted, free of charge, to any person obtaining a      *
* copy of this software and associated documentation files (the                *
* "Software"), to deal in the Software without restriction, including          *
* without limitation the rights to use, copy, modify, merge, publish,          *
* distribute, sublicense, and/or sell copies of the Software, and to           *
* permit persons to whom the Software is furnished to do so, subject to        *
* the following conditions:                                                    *
*                                                                              *
* The above copyright notice and this permission notice shall be included      *
* in all copies or substantial portions of the Software.                       *
*                                                                              *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS      *
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF                   *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.       *
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY         *
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,         *
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE            *
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                       *
*******************************************************************************/
package uk.ac.ic.doc.kevlar.core.framework.internal.execute;

import java.util.HashSet;
import java.util.Set;

import uk.ac.ic.doc.kevlar.api.programs.returnValues.IReturnMapping;
import uk.ac.ic.doc.kevlar.api.programs.returnValues.IReturnModel;
import uk.ac.ic.doc.kevlar.core.framework.internal.IProgramInstance;
import uk.ac.ic.doc.kevlar.core.framework.internal.IReturnValue;
import uk.ac.ic.doc.kevlar.core.framework.internal.programs.IProgramExitListener;

/**
 * @author tora
 */
class ProgramInstanceImpl implements IProgramInstance {

    final Process p;

    private final IReturnModel retMod;

    final Set<IProgramExitListener> notifiers;

    final Runnable traceRunnable;
    
    ProgramInstanceImpl(Process p, IReturnModel retMod) {
        this.p = p;
        this.retMod = retMod;
        notifiers = new HashSet<IProgramExitListener>();

        traceRunnable = new Runnable() {

            public void run() {
                Thread.currentThread().setName("Execution-Waiting Thread");

                try {
                    ProgramInstanceImpl.this.p.waitFor();
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }

                synchronized ( notifiers ) {
                    for( IProgramExitListener list : notifiers ) {
                        list.programExited(ProgramInstanceImpl.this);
                    }
                }
            }

        };
    }

    public boolean isRunning() {
        // XXX: toa02: there has to be a better way of doing this!
        try {
            p.exitValue();
        } catch (IllegalThreadStateException itse) {
            return true;
        }

        return false;
    }

    public void kill() {
        p.destroy();
    }

    public Runnable getTraceRunnable() {
        return traceRunnable;
    }
    
    public void addExitNotifier(IProgramExitListener notifer) {

        synchronized (notifiers) {
            if (isRunning()) {
                notifiers.add(notifer);
                return;
            }
        }

        notifer.programExited(this);
    }

    public IReturnValue getReturnValue() {

        final int retVal;
        try {
            retVal = p.waitFor();
        } catch (InterruptedException e) {
            throw new AssertionError("Precondition Failed");
        }

        final IReturnMapping irm = retMod.getReturnValueMap().get(
                Integer.valueOf(retVal));

        if (irm == null) {
            return new IReturnValue() {

                public int getLiteralReturnValue() {
                    return retVal;
                }

                public String getReturnDescription() {
                    return "No Return Description Provided For this Value";
                }

                public boolean isErroredReturn() {
                    return true;
                }

            };

        } else {
            return new IReturnValue() {

                public int getLiteralReturnValue() {
                    return retVal;
                }

                public String getReturnDescription() {
                    return irm.getMessage();
                }

                public boolean isErroredReturn() {
                    return !irm.isGood();
                }

            };
        }
    }

}
