package condor.gahp.gass;

import condor.gahp.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.ByteArrayOutputStream;

import org.gridforum.ogsi.ExtendedDateTimeType;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.gridforum.jgss.ExtendedGSSManager;
import org.gridforum.jgss.ExtendedGSSCredential;

import org.globus.io.gass.server.GassServer;


public class GassServerInitHandler implements CommandHandler {

    private GahpInterface gahp;

    public void setGahp (GahpInterface gahp) {
        this.gahp = gahp;
    }

    public CommandHandlerResponse handleCommand (String[] cmd) {

        String fileName = null;
        Integer requestId = null;

        try {
            requestId = new Integer(cmd[1]);
        }
        catch (Exception e) {
            e.printStackTrace(System.err);
            return CommandHandlerResponse.SYNTAX_ERROR;
        }

        return new CommandHandlerResponse (CommandHandlerResponse.SUCCESS,
                      new GassServerInitRunnable (requestId.intValue(), gahp));
    } // handleCommand

    class GassServerInitRunnable implements Runnable {
        public final int requestId;
        private GahpInterface gahp;
        private GassServer gassServer = null;
        
        public GassServerInitRunnable(int requestId, 
                                      GahpInterface gahp) {
            this.requestId = requestId;
            this.gahp = gahp;
        }
            
        public void run() {
            try {
                gassServer = new GassServer();
                gassServer.setOptions (GassServer.STDOUT_ENABLE |
                                       GassServer.STDERR_ENABLE |
                                       GassServer.READ_ENABLE |
                                       GassServer.WRITE_ENABLE);
                gassServer.registerDefaultDeactivator();
                gahp.addCleanupStep (
                                     new CleanupStep () {
                                         public void doCleanup() {
                                             if (gassServer != null)
                                                 gassServer.shutdown();
                                         }
                                     });
            }
            catch (Exception e) {
                e.printStackTrace(System.err);
                gahp.addResult (
                                requestId,
                                new String[] { "1", "null"}
                                ); 
            }
                
            gahp.addResult (requestId, new String[] { "0", gassServer.getURL()});
        }
    }
}
