/*
Copyright (C) 2005 mkraegeloh@sulis.de

purpose: call a webject through the ext/tools/ListAll.xml task, or another task if -t option given

This program is free software; you can redistribute it and/or modify it under the terms of the
GNU Lesser General Public License as published by the Free Software Foundation;
see http://www.gnu.org/licenses/lgpl.html (und deutsch: http://www.gnu.de/lgpl-ger.html)

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Lesser General Public License for more details.

*/
package ext.tools;

import wt.util.*;
import wt.method.*;
import java.util.regex.*;
import java.util.*;
import java.io.*;
import com.infoengine.object.factory.Group;
import com.infoengine.au.*;

/**
  * allow invokation of webjects/tasks via commandline.
  *
  * @author mkraegeloh
  * @version 1.0
  */
  // 20061124 mkr; add system.exit(0) (thanks lberger@ptc.com ;-) and added version as 1.01

public class RunListAll{
   public static final String CVSVersion = "$Header: /usr/local/cvsroot/SULIS/src/ext/tools/RunListAll.java,v 1.5 2007/01/22 10:41:43 mkr Exp $";
   private static String version="1.01";
   public static void main(String[] args) throws Exception {
	if(args.length == 0){
	   System.out.println("RunListAll version="+version);
	   System.out.println("usage: RunListAll [-t task] [-i instance] [[-c|-e] [-m]] [-r]  webject-name [param data] ...");
	   System.out.println("       -c outputs csv, -m adds group metadata, -e outputs element-xml -r rotates the group");
	   System.exit(1);
	}
	try{
	char[] ca;
	ToolUtils.fixEscapes(args);
	// see if user has passed iso8859 instead of utf8 on cmdline args ...
	for(int i=0;i<args.length;i++){
	   ca=args[i].toCharArray();
	   for(int j=0;j<ca.length;j++){
		if(ca[j] == 0xfffd){
		   System.out.println("ERROR: found \\xFFFD in args - assuming bad encoding settings.");
		   System.exit(1);
		}
	   }
	}
	boolean wantXML=true;
	int addMeta=0;
	boolean elementsXml=false;
	boolean rotate=false;
	WTContext.init(args);
	if(!WTContext.getContext().getLocale().getLanguage().equals("en")){
	   //System.out.println("INFO: switching language from "+WTContext.getContext().getLocale().getLanguage()+" to en");
	   WTContext.getContext().setLocale(Locale.ENGLISH);
	}
	Hashtable form=new Hashtable();
	Hashtable param=new Hashtable();
	int off=0;
	String task="ext/tools/ListAll";
	boolean needGroupIn=false;
	while(off< args.length && args[off].startsWith("-")){
	   if(args[off].equals("-i")){ form.put("INSTANCE",args[off+1]); off+=2; }
	   else if(args[off].equals("-t")){ task=args[++off]; off++; }
	   else if(args[off].equals("-e")){ elementsXml=true; off++; }
	   else if(args[off].equals("-c")){ wantXML=false; off++; }
	   else if(args[off].equals("-m")){ addMeta++; off++; }
	   else if(args[off].equals("-r")){ rotate=true; off++; }
	   else{ System.out.println("ignoring unknown option "+args[off]); off++; }
	}
	String oldval;
	Vector v;
	Object o;
	// no overridden task argument means we invoke generic task which will construct a webject invocation.
	if(task.equals("ext/tools/ListAll")){
	   form.put("WEBJECT_NAME",args[off++]);
	   for(int i=off;i<args.length;i+=2){
		if((o=param.get(args[i]))!=null){
		   if(o instanceof Vector)
			((Vector)o).add(args[i+1]);
		   else{
			param.put(args[i],v=new Vector());
			v.add(o);
			v.add(args[i+1]);
		   }
		}
		else
		   param.put(args[i],args[i+1]);
	   }
	}
	// users tasks ...
	else{
	   // fix supporting-adapter . -> instance
	   for(int i=off;i<args.length;i+=2){
	      if(args[i].equalsIgnoreCase("supporting-adapter") && args[i+1].equals(".")){
		    WTProperties props = WTProperties.getLocalProperties();
		    args[i+1]=props.getProperty("wt.federation.ie.VMName");
		    break;
		}
	   }
	   for(int i=off;i<args.length;i+=2){
		if((o=form.get(args[i]))!=null){
		   if(o instanceof Vector)
			((Vector)o).add(args[i+1]);
		   else{
			form.put(args[i],v=new Vector());
			v.add(o);
			v.add(args[i+1]);
		   }
		}
		else
		   form.put(args[i],args[i+1]);
	   }
	}
	//Group g = ToolUtils.callTask(form,null,task,param);
	Group g = (Group) RemoteMethodServer.getDefault().invoke("callTask", "ext.tools.ToolUtils", null,
	   new Class[] {Hashtable.class, Group.class, String.class, Hashtable.class },
	   new Object[] {form, null, task, param });
	if(g != null){
	   Object err=g.getAttributeValue(0,"exception-object");
	   if(err != null){
		System.out.println("found exception:"+err);
		if(err instanceof Exception)
		   ((Exception)err).printStackTrace();
	   }
	   System.err.println("GROUP SUCCESS: "+g.getSuccess());
	   if(rotate)
	      ToolUtils.rotGroup(g);
	   if(! wantXML)
		System.out.println(ToolUtils.group2csv(g,"\t","\n",true));
	   else if(! elementsXml)
	      g.toXML(new java.io.PrintWriter(System.out), true, addMeta > 0);
	   else
	      for(int i=0;i<g.getElementCount();i++)
		   g.getElementAt(i).toXML(new java.io.PrintWriter(System.out),addMeta > 0);
	}
	else
	   System.out.println("null group!");
   }
   catch(Exception e){
      System.out.println("caught exception:");
	e.printStackTrace();
   }
   System.exit(0);
}
}
