package e4s.tutorial;

import e4s.html.*;
import e4s.html.input.extended.*;
import e4s.servlet.*;

/**
 * A form for entering values using different types of fields.
 *
 * {@tutorial Example_InputForm}
 */
public class Example_InputForm extends E4ModuleImplementation
{
   public static E4Method initForm = null;
   public static E4Method saveValues = null;
 
   
   public E4Fieldset declareFormFields(FORM form)
   {
      E4Fieldset res = form.FIELDSET();
      
      TEXTFIELD firstname = res.TEXTFIELD(new E4InputFieldName("NAME1"),"Firstname",20);

      TEXTFIELD lastname = res.TEXTFIELD(new E4InputFieldName("NAME2"),"Lastname",10,20);
      lastname.layoutToNextRow(false); 

      FLOATFIELD weight = res.FLOATFIELD(new E4InputFieldName("WEIGHT"),"Weight",8);
      weight.setValidation(0.0f,200.0f);
      // weight.layoutToNextRow(true); 
       
      LONGFIELD age = res.LONGFIELD(new E4InputFieldName("AGE"),"Age",3);
      age.layoutToNextRow(false); 
      age.setValidation(1,99);
      
      CHECKBOX smoker = res.CHECKBOX(new E4InputFieldName("SMOKER"),"Do you smoke?");
      smoker.layoutToNextRow(false);

      HIDDENFIELD hiddenfield = res.HIDDENFIELD(new E4InputFieldName("REFERENCE_NUMBER"));
      hiddenfield.setValue(12345);
         
      SELECT preferences = res.SELECT(new E4InputFieldName("BUSINESS"),"Your business",new String[]{ "None", "Student", "Worker", "Manager" });
      
      DATEFIELD birthdate = res.DATEFIELD(new E4InputFieldName("BORN"),"Birthdate");
         
      // res.setBorder(true);
      
      res.setLegend("Your personal data");

      return res;
   }
   
   public void initForm( HTML html )
   {
      FORM form = html.BODY().FORM();
      
      declareFormFields(form);
      
      form.setAction(saveValues);
      form.FORM_Submit("Proceed");
      form.FORM_Reset("Clear");
   }
   
   public void saveValues( HTML html, E4CgiParams p )
   throws Exception
   {
      BODY body = html.BODY();

      FORM form = new FORM( html.E4ID(), "Example");
      E4Fieldset person_fields = declareFormFields(form);
      
      person_fields.setValue(p);
      
      if (! person_fields.validate(getServlet()))
      {
         body.addElement(form);
         
         form.setAction(saveValues);
         form.FORM_Submit("Proceed");
         form.FORM_Reset("Clear");
         
         form.B(true);
         form.print("Validation failed, please try your input again");
         form.B(false);
         form.BR();
      }
      else
      {
         body.println("Your input can be processed now, you entered:");
         body.BR();
         
         TABLE test = body.TABLE();
         p.toTable(test);
         
         body.P();
         
         A href = body.A(initForm);
         href.print("[start again]");
      }
   }
}