
// GenClass.java
// Girish Managoli, Alan Monnox
// https://opensource.com/article/19/12/generate-code-apache-velocity
// https://www.informit.com/articles/article.aspx?p=389718&seqNum=2

// Modified by Andrew Davison, ad@coe.psu.ac.th, July 2023

/* Generate a Java class with a main() function that creates an object.
   The classname is the first command line argument,
   and the other arguments are a series of field names and their
   types formatted as name:type. They become private fields 
   and get/set methods.
   There's also a toString() method for printing the fields.
   The class is saved in <className>.java.

   Usage:
    > compile GenClass.java
    > run GenClass <className> <fieldName:type>*
   e.g.
    > run GenClass Foo name:String id:int
         // generates Foo.java with two fields and get/set methods
*/

import java.io.*;
import java.util.*;

import org.apache.velocity.app.*;
import org.apache.velocity.*;
import org.apache.velocity.tools.generic.*;


public class GenClass
{
  private static final String TEMPLATE_FNM = "jclass.vm";


  public static void main(String args[])  throws Exception
  {
    if (args.length < 1) {
      System.out.println("Usage: run GenClass <className> <fieldName:type>*");
      return;
    }

    // split each name:type argument into two lists
    List<String> names = null;
    List<String> types = null;
    if (args.length > 1) {
      names = new ArrayList<>();
      types = new ArrayList<>();
      for (int i=1; i < args.length; i++) {  // skip the first command line arg
         String[] field = args[i].split(":");
         System.out.println("field " + i + ": " + 
                                 Arrays.toString(field));
         if (field.length == 2) {
           names.add(field[0]);
           types.add(field[1]);
         }
         else
           System.out.println("Could not parse " + args[i]);
      }
    }

    Velocity.init();
    System.out.println("Loading template: " + TEMPLATE_FNM);
    Template template = Velocity.getTemplate(TEMPLATE_FNM);
     
    VelocityContext vc = new VelocityContext();
    vc.put("dateTool", new ComparisonDateTool());  // load tools
    vc.put("esc", new EscapeTool());

    vc.put("className", args[0]);
    if (names != null) {
      vc.put("names", names);
      vc.put("types", types);
    }

    String fnm = args[0] + ".java";
    System.out.println("\nGenerating " + fnm);
    Writer w = new FileWriter(new File(fnm));
    template.merge(vc, w);
    w.flush();
    w.close();
  } /* main */

}  // end of GenClass class
