package eu.dnetlib.espas.gui.client;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.core.client.GWT;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.sencha.gxt.data.shared.TreeStore;

public class ToolTipCell extends AbstractCell<String> {
	
	private TreeStore<BaseDto> store;
    private boolean showTooltip;
	
	public ToolTipCell(TreeStore<BaseDto> store, boolean showTooltip) {
		super();
		this.store = store;
        this.showTooltip = showTooltip;
	}
	
    interface Templates extends SafeHtmlTemplates {
    	
      @SafeHtmlTemplates.Template("<div qtip=\"{0}\" qtitle=\"{1}\">{2}</div>")
      SafeHtml cellWithToolTip(String tooltip, String title, SafeHtml value);
      
      @SafeHtmlTemplates.Template("<div>{0}</div>")
      SafeHtml cellWithoutToolTip(SafeHtml value);
      
      @SafeHtmlTemplates.Template("<div style=\"font-weight:bold\">{0}</div>")
      SafeHtml headerCellWithoutTooltip(SafeHtml value);
      
      @SafeHtmlTemplates.Template("<div qtip=\"{0}\" style=\"font-weight:bold\">{1}</div>")
      SafeHtml headerCellWithTooltip(String tooltip, SafeHtml value);
    }

    private static Templates templates = GWT.create(Templates.class);

	@Override
	public void render(Context context, String value, SafeHtmlBuilder shb) {
		
		if (value == null) {
			return;
		}

		SafeHtml safeValue = SafeHtmlUtils.fromString(value);
      
		BaseDto bdto = store.findModelWithKey(context.getKey().toString());
		String tooltip = bdto.getDescription();
      
		SafeHtml rendered;
		if(bdto.isHeader()) {
			if(tooltip==null || tooltip.equals("") || !showTooltip) {
				rendered = templates.headerCellWithoutTooltip(safeValue);
			} else {
				rendered = templates.headerCellWithTooltip(tooltip, safeValue);
			}
		} else {
			if(tooltip==null || tooltip.equals("") || !showTooltip) {
				rendered = templates.cellWithoutToolTip(safeValue);
			} else {
				rendered = templates.cellWithToolTip(tooltip, value ,safeValue);
			}
		}
		shb.append(rendered);
	}
}
