import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import javax.naming.Context;
import javax.naming.NamingException;

import weblogic.jndi.Environment;
import worklist.TaskCreationSync;

import com.bea.wli.bpm.proxy.JpdProxy;
import com.bea.worklistSample.inputData.InputDataDocument;


public class CreateAndAssignTasks
{
  private InputDataDocument[] inputDocs;

  /**
   * 
   */
  public void init(HashMap props)
  throws Exception
  {
    File inputDocStore = new File((String)props.get("input.document.store"));
    File[] inputFiles = inputDocStore.listFiles();

    ArrayList list = new ArrayList();
    for(int i=0; i<inputFiles.length; i++)
      list.add(InputDataDocument.Factory.parse(inputFiles[i]));
    
    inputDocs = (InputDataDocument[]) list.toArray(new InputDataDocument[0]);
  }
  
  /**
   * 
   */
  public void execute()
  throws Exception
  {
    for(int i=0; i<inputDocs.length; i++)
    {
      // proxy has to be created here to start a new conversation for each call
      TaskCreationSync process = createProxy();
      process.recieveTaskCreationRequest(inputDocs[i]);
    }
  }
  
  private TaskCreationSync createProxy()
  throws Exception
  {
    return (TaskCreationSync) JpdProxy.create( 
      TaskCreationSync.class, TaskCreationSync.SERVICE_URI, 
      new JpdProxy.ContextHandler()
      {
        public Context getContext() throws NamingException
        {
          Environment env = new Environment();
          env.setProviderUrl(System.getProperty("server.url"));
          env.setSecurityPrincipal(System.getProperty("user"));
          env.setSecurityCredentials(System.getProperty("password"));
          return env.getInitialContext();
        }
      });
  }
  

  /**
   * Test a Single Iteration 
   */
  public static void main(String[] args)
  {
    CreateAndAssignTasks client = new CreateAndAssignTasks();

    try
    {
      HashMap props = new HashMap();
      props.put("input.document.store", System.getProperty("input.document.store"));
      client.init(props);
      client.execute();
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
  }
  
}


