package org.zkforge.converters;

import javax.servlet.ServletException;

import org.zkoss.web.fn.ServletFns;
import org.zkoss.zk.ui.Component;
import org.zkoss.zkplus.databind.TypeConverter;
import org.zkoss.zul.Html;
import org.zkoss.zul.Image;
import org.zkoss.zul.Listcell;

/**
 @author Robert Pichelhofer
 
 * Databindingconverter
 * Direction: Output only
 
 * Source: boolean
 * Destination; Images for Labels, Listecells and Images...
 
 * Examples:
 <listcell label="@{person.married}, converter:org.zkforge.converters.BooleanImage"/>
 <image src="@{person.married}, converter:org.zkforge.converters.BooleanImage"/>
 <label> not supported --> use <image..> instead
 
 * Pictures:
 * Has to be in package web.conv.img
 
 * TODO: Label, try with style, background-image 
 * TODO: allow a imagepath override via zk preference
 
 */
public class BooleanImage implements TypeConverter {

  private final String trueImageSrc;
  private final String falseImageSrc;
  private final String trueImageUrl;
  private final String falseImageUrl;
  
  public BooleanImage () throws ServletException {
      trueImageSrc = "~./conv/img/true.gif";
      falseImageSrc = "~./conv/img/false.png";
      trueImageUrl = "<image src=\"" + ServletFns.encodeURL(trueImageSrc"\"/>";
      falseImageUrl = "<image src=\"" + ServletFns.encodeURL(falseImageSrc"\"/>";
  }
  /* (non-Javadoc)
   * @see org.zkoss.zkplus.databind.TypeConverter#coerceToBean(java.lang.Object, org.zkoss.zk.ui.Component)
   */
  public Object coerceToBean(Object arg0, Component arg1) {
    // this is an output converter, no action here
    return null;
  }

  /* (non-Javadoc)
   * @see org.zkoss.zkplus.databind.TypeConverter#coerceToUi(java.lang.Object, org.zkoss.zk.ui.Component)
   */
  public Object coerceToUi(Object arg0, Component arg1) {
    if (arg0 == null) {
      return null;
    }
    boolean input = (Booleanarg0;
    
    // Handle the different destination-components
    if (arg1 instanceof Listcell) {
      Listcell cell = (Listcellarg1;
      cell.setImage(getImageSrc(input));
    else if (arg1 instanceof Image) {
      // return the ImageSrc for the src-attribute
      return getImageSrc(input);
    else {
      // try a generic way for all other components
      // add a html-child to the destination component
      new Html(getImageUrl(input)).setParent(arg1);
    }
    // we've changed the component, so there is no need for returnvalue
    return null;
  }
  /*
   * get the imagepath
   */
  private String getImageSrc(boolean _boolean) {
    if (_boolean) {
      return trueImageSrc;
    else {
      return falseImageSrc;
    }
  }
  /*
   * get the html-format for image
   */
  private String getImageUrl(boolean _boolean) {
    if (_boolean) {
      return trueImageUrl;
    else {
      return falseImageUrl;
    }
  }
}