/*******************************************************************************
* 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.                       *
*******************************************************************************/
/*
 * Created on Dec 21, 2004
 */
package uk.ac.ic.doc.kevlar.core.programs.coreUtils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;

import uk.ac.ic.doc.kevlar.api.programs.arguments.IArgumentInstance;
import uk.ac.ic.doc.kevlar.core.types.textType.ITextType;
import uk.ac.ic.doc.kevlar.core.types.textType.TextTypeImpl;
import uk.ac.ic.doc.kevlar.publicInterfaces.AbstractProgram;
import uk.ac.ic.doc.kevlar.publicInterfaces.IInputPipe;
import uk.ac.ic.doc.kevlar.publicInterfaces.IOutputPipe;

/**
 * @author tora
 */
public class SysExec extends AbstractProgram {

    public void run(IArgumentInstance args, Map<String, IInputPipe> inputs,
            Map<String, IOutputPipe> outputs) {

        String command = args.getText("Command");
        if( command == null ) {
            return;
        }
        
        IInputPipe iip = inputs.get("In");
        IOutputPipe iop = outputs.get("Out");
        
        ProcessBuilder pb = new ProcessBuilder();
        
        pb.command(command.split(" "));
        
        try {
            Process p = pb.start();

            BufferedReader bis = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedWriter bos = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
            
            Thread a = null;
            Thread b = null;
            if( iip != null ) {
                a = new Thread( new OutputHandler(bos,iip));
                a.start();
            }
        
            if( iop != null ) {
                b = new Thread( new InputHandler(bis,iop));
                b.start();
            }
            
            int i = p.waitFor();
            
            if( a != null ) {
                a.join();
            }
            if( b!= null ) {
                b.join();
            }
            
            exit(i);
            return;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        exit(1);
        return;
    }

    static class InputHandler implements Runnable {
        
        private BufferedReader bis;
        private IOutputPipe iop;
        
        public InputHandler(BufferedReader bis, IOutputPipe iop) {
            this.bis = bis;
            this.iop = iop;
        }
        
        public void run() {

            String s;
            
            try {
                while( null != ( s = bis.readLine() )) {
                    iop.write(new TextTypeImpl(s));
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (IllegalStateException ise) {
                /* we're done */
            }
            
            try {
                bis.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            iop.close();
        }
        
    }

    static class OutputHandler implements Runnable {
 
        final private BufferedWriter bos;
        final private IInputPipe iis;
        
        public OutputHandler( BufferedWriter bos, IInputPipe iis) {
            this.bos = bos;
            this.iis = iis;
        }
        
        
        public void run () {
            try {
                while( true ) {
                    bos.write(((ITextType)iis.read()).toString());
                    bos.flush();
                }
            } catch (IOException e) {
                /* we're fine */
            } catch (InterruptedException e) {
                /* we're fine */
            } catch (IllegalStateException ise) {
                /* we're fine */
            }
            
            iis.close();
            try {
            bos.close();
            } catch (IOException e ) {
                /* */
            }
        }
        
    }
}
