package jwebform.field;

import java.util.Optional;
import jwebform.env.Env.EnvWithSubmitInfo;
import jwebform.field.helper.OneValueTypeProcessor;
import jwebform.field.structure.FieldResult;
import jwebform.field.structure.SingleFieldType;
import jwebform.field.structure.StaticFieldInfo;
import jwebform.validation.ValidationResult;

public class NumberType implements SingleFieldType {

  private final int initialNumber;

  public final OneValueTypeProcessor oneValueType;

  public NumberType(String name, int initialValue) {
    this.oneValueType = new OneValueTypeProcessor(name, Integer.toString(initialValue));
    initialNumber = initialValue;
  }

  @Override
  public FieldResult apply(EnvWithSubmitInfo env) {
    String requestVal = env.getEnv().getRequest().getParameter(oneValueType.name);
    int parsedNumber = 0;
    String parsedNumberVal = "";
    ValidationResult vr = ValidationResult.undefined();
    Optional<Integer> numbOptional;

    if ("".equals(requestVal)) {
      numbOptional = Optional.empty();
    } else {
      String val = env.isSubmitted() ? requestVal : Integer.toString(initialNumber);
      try {
        parsedNumber = Integer.parseInt(val);
        parsedNumberVal = Integer.toString(parsedNumber);
        numbOptional = Optional.of(parsedNumber);
      } catch (NumberFormatException e) {
        vr = ValidationResult.fail("jformchecker.not_a_number");
        parsedNumber = 0;
        numbOptional = Optional.empty();
      }
    }
    return FieldResult.builder().withValue(parsedNumberVal)
        .withStaticFieldInfo(new StaticFieldInfo(oneValueType.name, t -> "<!-- number -->", 1))
        .withValidationResult(vr).withValueObject(numbOptional).build();
  }


  @Override
  public String toString() {
    return String.format("NumberInput. name=%s", oneValueType.name);
  }


}

@@ -799,16 +799,73 @@
 .name);%0A
+    ValidationResult vr = ValidationResult.undefined();%0A%0A
     int 
@@ -923,97 +923,226 @@
     
-ValidationResult vr = ValidationResult.undefined();%0A    Optional%3CInteger%3E numbOptional;%0A%0A
+Optional%3CInteger%3E numbOptional;%0A    if (!env.isSubmitted()) %7B%0A      parsedNumber = initialNumber;%0A      numbOptional = Optional.of(initialNumber);%0A      parsedNumberVal = Integer.toString(parsedNumber);%0A    %7D else %7B%0A  
     
@@ -1172,24 +1172,26 @@
 l)) %7B%0A      
+  
 numbOptional
@@ -1211,24 +1211,26 @@
 mpty();%0A    
+  
 %7D else %7B%0A   
@@ -1228,24 +1228,26 @@
 lse %7B%0A      
+ 
+ 
 String val =
@@ -1323,14 +1323,18 @@
     
+  
 try %7B%0A
+  
     
@@ -1375,32 +1375,34 @@
 t(val);%0A        
+  
 parsedNumberVal 
@@ -1427,32 +1427,34 @@
 (parsedNumber);%0A
+  
         numbOpti
@@ -1493,16 +1493,18 @@
 ;%0A      
+  
 %7D catch 
@@ -1527,24 +1527,26 @@
 eption e) %7B%0A
+  
         vr =
@@ -1604,32 +1604,8 @@
 ;%0A  
-      parsedNumber = 0;%0A
     
@@ -1637,24 +1637,34 @@
 al.empty();%0A
+        %7D%0A
       %7D%0A    

Fix default value for number - type