package com.fujitsu.iflowqa.testframe;


/*
 * ImportCreateProcessXML.java
 *
 * Created on August 2, 2004, 5:23 PM
 */


//i-Flow packages
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;

import com.fujitsu.iflow.model.util.ModelInternalException;
import com.fujitsu.iflow.model.workflow.Plan;
import com.fujitsu.iflow.model.workflow.ProcessInstance;
import com.fujitsu.iflow.model.workflow.WFAdminSession;
import com.fujitsu.iflow.model.workflow.WFObjectFactory;

public class ImportCreateProcessXML
{
    public static void main(String args[]) throws Exception
    {
    if(args.length != 3){
        System.out.println("Run Time Arguments Required: String userID, String userPassword, String propPath");
        System.out.println("Press any key to exit...");
        getStringInput();
    }
        log("=======================================================");
        log("This is a sample program showing how to ");
        log("1. Sign in to i-Flow Server using the WFAdminSession.");
        log("2. Import the chosen template.");
        log("3. Sign out from i-Flow Server.");
        log("=======================================================");
        ImportCreateProcessXML test = new ImportCreateProcessXML();
        log("Press Enter to login...");
        getStringInput();
        test.connect(args[0],args[1],args[2]);
        if ( test.isConnected() )
        {
            log("Enter path to the directory to retrieve templates from (e.g. c:/iflow_attachments):");
            String templatesPath = getStringInput();
            File f = new File(templatesPath);
            String choice = null;
            String xmlTemplate = null;

            if (f != null && f.exists())
            {
               String[] name = f.list();
               for (int i=0; i < name.length; i++)
               {
                 log("FYI -- File Name in " + templatesPath + " : " + name[i]);
                 if (name[i].endsWith(".XML") || name[i].endsWith(".xml"))
                 {
                    log("FYI -- Found the file ending with .xml --> " + name[i]);
                    log("Press Enter to import this template or 'n' to skip:");
                    choice = getStringInput();
                    if (choice != null && choice.equalsIgnoreCase("n"))
                    {
                        // do nothing.
                    }
                    else if (choice != null && !choice.equalsIgnoreCase("n"))
                    {
                        xmlTemplate = test.loadXMLTemplate(templatesPath+"/"+name[i]);
                        if (xmlTemplate != null)
                        {
                           Plan plan = test.session.createPlanFromXML(xmlTemplate);
                           plan.setWFSession(test.session);
                           if (plan != null)
                           {
                              log("Plan created!");
                              log("Name: " + plan.getName());
                              log("ID: " + plan.getId());
                              log("\n\n");
                              ProcessInstance pi = plan.createProcessInstance();
                              log("Process created!");
                              log("Name: " + pi.getName());
                              log("ID: " + pi.getId());
                              log("\n\n");
                              try
                              {
                               pi.start();
                              } catch(Exception e){ continue; }
                              log("Process started!");
                           }
                        }
                    }

                 }
                } // end for loop
            } // end if
            else
            {
                log("Error: cannot find the directory specified");
            } // end else

            log("Press enter to disconnect...");
            getStringInput();
            test.disconnect();
        }
        System.exit(0);
    }


    private String loadXMLTemplate(String templatePathName)
    {
       File template = new File(templatePathName);
       FileReader filereader = null;
       BufferedReader bufferedreader = null;
       String instring = null;
       String xmlString = "";
       try {
         if (template != null && template.exists())
         {
             filereader = new FileReader(templatePathName);
             // checking whether the stream is ready to be read
             // if not ready, then rebuild.

             do
             {
                    bufferedreader = new BufferedReader(filereader);
             } while (!(bufferedreader.ready()));

             do
             {
                instring = null;
                instring = bufferedreader.readLine(); //  read the next line
                if (instring == null)
                {
                   break; // exit the do-while block
                }

                xmlString += instring;

             } while (instring != null);

             return xmlString;
         }
         else return null;

       } catch (Exception ex)
       {
          ex.printStackTrace();
          return null;
       } finally {
          try {
            if (filereader != null) filereader.close();
            if (bufferedreader != null) bufferedreader.close();
          } catch (Exception ex2) {
            ex2.printStackTrace();
          }
       }



    }

    private String getProcessState(int processState)
    {
         if (processState == ProcessInstance.STATE_CLOSED)
         {
             return "CLOSED";
         }
         else if (processState == ProcessInstance.STATE_CREATED)
         {
             return "CREATED";
         }
         else if (processState == ProcessInstance.STATE_OPEN)
         {
             return "OPEN";
         }
         else if (processState == ProcessInstance.STATE_RUNNING)
         {
             return "RUNNING";
         }
         else return "UNKNOWN";
    }



    private void showFileProps(File file1) throws Exception
    {
        log("FYI -- File: " + file1.getName() + (file1.isFile() ?
           " is a file" : " is a named pipe or directory"));
        log("FYI -- Size: " + file1.length());
        log("FYI -- Path: " + file1.getPath());
        log("FYI -- Absolute Path: " + file1.getAbsolutePath());
        log("FYI -- File was last modified: " + (new Date(file1.lastModified())).toString());
        log("FYI -- " + (file1.exists() ? "File exists" :
            "File does not exist"));
        log("FYI -- " + (file1.canRead() ? "File can be read from" :
            "File cannot be read from"));
        log("FYI -- " + (file1.canWrite() ? "File can be written to" :
            "File cannot be written to"));
        log("FYI -- " + (file1.isDirectory() ? "File is a directory" :
            "File is not a directory"));
    }




     public void connect(String userID, String userPassword, String propPath) throws Exception
     {
          Properties props = new Properties();
          //props.put("java.naming.provider.url","rmi://"+hostname+":"+serverPort);
          //props.put("TWFTransportType","RMI");
          FileInputStream fis = new FileInputStream(propPath);
          props.load(fis);
          fis.close();
          try {
            /*
                 String[] names = Naming.list("rmi://" + hostname + ":" + serverPort);
                 for (int i=0; i < names.length; i++)
                 {
                    log("JNDI name ------> :\t" + names[i]);
                 }
            */
                 session = WFObjectFactory.getWFAdminSession();
                 log("Debug: ImportCreateProcessXML: connect: WFAdminSession created.");
          }
          catch (ModelInternalException mie) {
              log("Error: ImportCreateProcessXML: connect: fail to obtain WFAdminSession object.");
          mie.printStackTrace();
          }

          session.initForApplication(null,props);
          String iFlowServer = (session.getServerList())[0]; // use the 1st Server on the array.
          log("Debug: ImportCreateProcessXML: connect: Server retrieved is called: " + iFlowServer);
          try {
              log("Debug: ImportCreateProcessXML: connect: before session.logIn();");
              session.logIn(iFlowServer,userID,userPassword);
              userID = session.getUserName();
              log("Debug: ImportCreateProcessXML: connect: user, " + userID + ", connected to i-Flow Server!");
              connected = true;
          }
          catch (Exception e)
          {
              log("Debug: ImportCreateProcessXML: connect: fail to connect to i-Flow server.");
              e.printStackTrace();
          }
  }



  public void disconnect() throws Exception
  {
          try
          {
              if (this.connected)
              {
                  String username = this.session.getUserName();
                  this.session.logOut();
                  log("Debug: ImportCreateProcessXML: disconnect: " + username + " disconnected from i-Flow server.");
                  this.connected = false;
              }
          }
          catch (Exception e)
          {
             log("Debug: ImportCreateProcessXML: disconnect: fail to disconnect from server.");
             e.printStackTrace();
          }
  }



  public boolean isConnected() throws Exception
  {
      return this.connected;
  }



  public static void log(String s) {
      if (VERBOSEandTIMESTAMP)
      {
         String dateStr =  (new Date()).toString();
         System.out.println("[" + dateStr + "]" + "\ti-FLOW: " + s);
      }
  }


  public static String getStringInput() throws IOException
  {
    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader br = new BufferedReader(isr);
    String str = br.readLine();
        return str;
  }


   /**
     *
     */
    public static long getLongInput() throws IOException
    {
         String str = getStringInput();
         return Long.parseLong(str);
    }

  // Instance variables
  WFAdminSession session;
  private boolean connected = false;
  private static final boolean VERBOSEandTIMESTAMP = true;
}