package com.fathomdb.cli;

import java.lang.reflect.Constructor;
import java.text.MessageFormat;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.OptionDef;
import org.kohsuke.args4j.spi.OptionHandler;
import org.kohsuke.args4j.spi.Parameters;
import org.kohsuke.args4j.spi.Setter;

public class StringWrapperOptionHandler<T> extends OptionHandler<T> {

    private static final String ILLEGAL_OPERAND = "\"{1}\" is not a valid value for \"{0}\"";

    public StringWrapperOptionHandler(CmdLineParser parser, OptionDef option, Setter<? super T> setter) {
        super(parser, option, setter);
    }

    @Override
    public int parseArguments(Parameters params) throws CmdLineException {
        String token = params.getParameter(0);
        try {
            Class<? super T> fieldType = setter.getType();
            Constructor<? super T> constructor = fieldType.getConstructor(String.class);
            T o = (T) constructor.newInstance(token);
            setter.addValue(o);
            return 1;
        } catch (Exception e) {
            throw new CmdLineException(MessageFormat.format(ILLEGAL_OPERAND, option.toString(), token));
        }
    }

    @Override
    public String getDefaultMetaVariable() {
        return "VAL";
    }
}

@@ -410,20 +410,17 @@
 r%3CT%3E %7B%0A%0A
-    
+%09
 private 
@@ -502,20 +502,17 @@
 0%7D%5C%22%22;%0A%0A
-    
+%09
 public S
@@ -605,24 +605,18 @@
 tter) %7B%0A
-        
+%09%09
 super(pa
@@ -638,27 +638,21 @@
 etter);%0A
-    %7D%0A%0A    
+%09%7D%0A%0A%09
 @Overrid
@@ -649,28 +649,25 @@
 %0A%09@Override%0A
-    
+%09
 public int p
@@ -725,24 +725,18 @@
 ption %7B%0A
-        
+%09%09
 String t
@@ -770,34 +770,19 @@
 0);%0A
-        try %7B%0A            
+%09%09try %7B%0A%09%09%09
 Clas
@@ -824,28 +824,19 @@
 Type();%0A
-            
+%09%09%09
 Construc
@@ -904,28 +904,19 @@
 class);%0A
-            
+%09%09%09
 T o = (T
@@ -949,28 +949,19 @@
 token);%0A
-            
+%09%09%09
 setter.a
@@ -972,28 +972,19 @@
 lue(o);%0A
-            
+%09%09%09
 return 1
@@ -985,24 +985,18 @@
 turn 1;%0A
-        
+%09%09
 %7D catch 
@@ -996,16 +996,24 @@
  catch (
+Security
 Exceptio
@@ -1023,20 +1023,159 @@
 ) %7B%0A
-            
+%09%09%09throw new CmdLineException(owner, MessageFormat.format(ILLEGAL_OPERAND, option.toString(), token));%0A%09%09%7D catch (ReflectiveOperationException e) %7B%0A%09%09%09
 thro
@@ -1197,16 +1197,23 @@
 ception(
+owner, 
 MessageF
@@ -1274,29 +1274,161 @@
 ));%0A
-        %7D%0A    %7D%0A%0A    
+%09%09%7D catch (IllegalArgumentException e) %7B%0A%09%09%09throw new CmdLineException(owner, MessageFormat.format(ILLEGAL_OPERAND, option.toString(), token));%0A%09%09%7D%0A%09%7D%0A%0A%09
 @Ove
@@ -1433,20 +1433,17 @@
 verride%0A
-    
+%09
 public S
@@ -1479,16 +1479,10 @@
 ) %7B%0A
-        
+%09%09
 retu
@@ -1495,12 +1495,9 @@
 L%22;%0A
-    
+%09
 %7D%0A%7D%0A

Fix exception handling in StringWrapperOptionHandler