/*
 * Created on Feb 17, 2006
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package gov.va.med.esr.ui.taglib.support;

import gov.va.med.fw.ui.valuelist.SelectableSearchValueListAdapter;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.mlw.vlh.ValueListInfo;
import net.mlw.vlh.web.ValueListConfigBean;
import net.mlw.vlh.web.tag.TableInfo;
import net.mlw.vlh.web.tag.support.ColumnInfo;
import net.mlw.vlh.web.tag.support.HtmlDisplayProvider;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * @author DNS   CHENB
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class HtmlDisplayCheckBoxSortingProvider extends HtmlDisplayProvider {
	protected transient Log logger = LogFactory.getLog(getClass());

	public static final String CHECKBOX_PARAM = "checkboxName";
    public static final String SELECTED_REQUEST_ATTRIBUTE_KEY = SelectableSearchValueListAdapter.SELECTED_REQUEST_ATTRIBUTE_KEY;

    
	public static String addScript(Object fieldName)
    {
        return "javascript:SelectedPaging(document, \'" + fieldName + "\', \'";
    }

	/**
	 * 
	 */
	public HtmlDisplayCheckBoxSortingProvider() {
		super();
		// TODO Auto-generated constructor stub
	}
		
    /**
     * Formats the text to be displayed as the header by wraping it in a link if
     * sorting is enabled. Alt (hint) is localized, please define in your
     * property file for messages the property "sorting"
     * 
     * @param columnInfo The ColumnInfo.
     * @param tableInfo The TableInfo.
     * @param info The ValueListInfo.
     * @return The formated HTML.
     */
    protected String doGetHeaderLabel(ColumnInfo columnInfo, TableInfo tableInfo,
            ValueListInfo info, Map includeParameters)
    {
    	/* THIS IMPLEMENTATION COPIED FROM VALUELIST 0.1.7 SRC; changed in one place below dealing with altSort value and usage */
    	
        StringBuffer sb = new StringBuffer();

        ValueListConfigBean config = tableInfo.getConfig();
        Map parameters = new HashMap(includeParameters);
        
        String altSort = "Sort " + columnInfo.getTitle();
        altSort = altSort.replaceAll("\\<.*?>"," ").replaceAll("&.*?;"," "); // strip out HTML and encoded characters

        if (columnInfo.getDefaultSort() != null)
        {
            // Get the current sort column and direction.
            String column = info.getSortingColumn();
            Integer direction = info.getSortingDirection();

            sb.append("<a href=\"").append(tableInfo.getUrl());

            parameters.put(ValueListInfo.PAGING_PAGE + tableInfo.getId(), "1");
            parameters.put(ValueListInfo.SORT_COLUMN + tableInfo.getId(),
                    columnInfo.getAdapterPropertyName());
            parameters
                    .put(
                            ValueListInfo.SORT_DIRECTION + tableInfo.getId(),
                            ((columnInfo.getAdapterPropertyName()
                                    .equals(column)) ? (ValueListInfo.ASCENDING
                                    .equals(direction) ? ValueListInfo.DESCENDING
                                    : ValueListInfo.ASCENDING)
                                    : columnInfo.getDefaultSort()));

            if (info.isFocusEnabled() == true)
            {
                parameters.put(ValueListInfo.DO_FOCUS + tableInfo.getId(), info
                        .isDoFocusAgain() ? "true" : "false");
                if (info.getFocusProperty() != null)
                {
                    parameters.put(ValueListInfo.FOCUS_PROPERTY
                            + tableInfo.getId(), info.getFocusProperty());
                }
                if (info.getFocusValue() != null)
                {
                    parameters.put(ValueListInfo.FOCUS_VALUE
                            + tableInfo.getId(), info.getFocusValue());
                }
            }

            sb.append(config.getLinkEncoder().encode(
                    tableInfo.getPageContext(), parameters));

            sb.append("\">").append(columnInfo.getTitle()).append("</a>");

            if (columnInfo.getAdapterPropertyName().equals(column))
            {
                sb.append(((isUsePadding()) ? "&nbsp;" : "")).append("<img alt=\"")
                		.append(altSort).append("\" ")
                		.append("src=\"")
                        .append(
                                getImageHome((HttpServletRequest) tableInfo
                                        .getPageContext().getRequest()))
                        .append("/sort(");
                sb
                        .append((ValueListInfo.ASCENDING.equals(direction) ? ValueListInfo.DESCENDING
                                : ValueListInfo.ASCENDING));
                sb.append(").png\" border=\"0\"/>");
            }
            else if (columnInfo.getDefaultSort() != null)
            {
                Locale locale = config.getLocaleResolver().resolveLocale(
                        (HttpServletRequest) (tableInfo.getPageContext()
                                .getRequest()));
                /*String altSort;
                try
                {
                    altSort = config.getDisplayHelper().help(
                            tableInfo.getPageContext(),
                            config.getMessageSource().getMessage("sorting",
                                    null, "Sort", locale));
                } catch (javax.servlet.jsp.JspException e)
                {
                	logger
                            .error("getHeaderLabel() - Error getting property 'sorting' : "
                                    + e.getMessage()
                                    + " Locale locale = "
                                    + locale
                                    + ", String column = "
                                    + column
                                    + " using defalt hint for sorting images.");

                    altSort = "Sort gsb " + columnInfo.getTitle();
                }*/

                sb.append(((isUsePadding()) ? "&nbsp;" : "")).append(
                        "<img alt=\"" + altSort + "\" src=\"").append(
                        getImageHome((HttpServletRequest) tableInfo
                                .getPageContext().getRequest())).append(
                        "/sort(null).png\" border=\"0\"/>");
            }
        }
        else
        {
            sb.append(columnInfo.getTitle());
        }

        return sb.toString();
    }
	
    /**
     * Formats the text to be displayed as the header by wraping it in a link if
     * sorting is enabled. Alt (hint) is localized, please define in your
     * property file for messages the property "sorting"
     * 
     * @param columnInfo The ColumnInfo.
     * @param tableInfo The TableInfo.
     * @param info The ValueListInfo.
     * @return The formated HTML.
     */
    public String getHeaderLabel(ColumnInfo columnInfo, TableInfo tableInfo,
            ValueListInfo info, Map includeParameters)
    {
    	includeParameters.remove(SELECTED_REQUEST_ATTRIBUTE_KEY);

        StringBuffer sb = new StringBuffer().append(
    		doGetHeaderLabel(columnInfo,
    		tableInfo, info, includeParameters));
        
        //insert javascript and document 
        if (includeParameters.containsKey(CHECKBOX_PARAM) 
        	&& sb != null && sb.indexOf("href=") > 0)
        {
        	//checkboxName=selected
        	int urlPos = sb.indexOf(tableInfo.getUrl());
        	if (urlPos >= 0)
        		sb.insert(urlPos, addScript(includeParameters.get(CHECKBOX_PARAM)));
        	
        	//insert script end ')
        	int endPos = sb.indexOf("\">");
        	if (endPos >= 0)
        		sb.insert(endPos, "\')");
        }
        
        return sb.toString();
    }
}
