package test.wicket.autocomplete.pages;

import org.apache.wicket.Response;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.IAutoCompleteRenderer;

/**
 * Represents the renderer for the choices that come from the ZipAndLocationField getChoices.
 */
public class CustomRenderer implements IAutoCompleteRenderer{
   public static final CustomRenderer INSTANCE = new CustomRenderer();
   private static int renderChoiceCalls = 0;
   /**
    * Creates an Instance of CustomRenderer.
    */
   public CustomRenderer(){
      
   }
   
   /**
    * Render the html header fragment for the completion. Usually the
    * html is written out by calling {@link Response#write(CharSequence)}.
    *
    * @param response
    */
   public void renderHeader(Response response) {
      //Write the table and header with all the properties for the auto-complete result's table
      response.write("<table class=\"dataview\" width=\"100%\" border=\"0\" align=\"left\" id=\"dataview\">");
   }
   /**
    * Render the html fragment for the given completion object. Usually the
    * html is written out by calling {@link Response#write(CharSequence)}.
    *
    * @param object
    *            completion choice object
    * @param response
    * @param criteria
    */
   public void render(Object object, Response response, String criteria) {
      //verify that the object parameter is not null
      if(object==null)
         return;
      //declare a string array variable to hold the cast.
      String[] data = (String[])object;
      if((renderChoiceCalls%2==0)){
         //open row
         response.write("<tr class=\"odd\" textvalue=\""+data[0]+data[1]+"\">");
      }else{
         //open row
         response.write("<tr class=\"even\" textvalue=\""+data[0]+data[1]+"\">");
      }
      renderChoiceCalls++;
      //country
      response.write("<td>");
      //verify that the result for zip code is not null
      if(data[0]!=null)
         response.write(data[0].replaceAll("\\\"", "&quot;"));
      response.write("</td>");
      //language column
      response.write("<td>");
      //verify that the result for location is not null
      if(data[1]!=null)
         response.write(data[1].replaceAll("\\\"", "&quot;"));
      
      response.write("</td>");
      
      //close row
      response.write("</tr>");
   }
   /**
    * Render the html footer fragment for the completion. Usually the
    * html is written out by calling {@link Response#write(CharSequence)}.
    *
    * @param response
    */
   public void renderFooter(Response response) {
      response.write("</table>");
   }  
}