/**
 * Licensed under the MICE s.r.l.
 * End User License Agreement
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.micegroup.it/voila/license.html
 */
package it.mice.voila.runtime.displaytag.basedec;

import it.mice.voila.runtime.entity.CoreEntity;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.servlet.jsp.JspWriter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.displaytag.decorator.TableDecorator;
import org.displaytag.exception.ObjectLookupException;
import org.displaytag.util.LookupUtil;

/**
 * @author ZZY9V4
 *         <p/>
 *         To change this generated comment edit the template variable "typecomment":
 *         Window>Preferences>Java>Templates.
 *         To enable and disable the creation of type comments go to
 *         Window>Preferences>Java>Code Generation.
 */
public class SelectRowPopupDec extends TableDecorator {

    /**
     * logger.
     */
    private static Log log = LogFactory.getLog(SelectRowPopupDec.class);

    /**
     * Called just within the TR tag. Can be subclassed to provide specific data to customize TR tag such as style, jscript events, etc...
     *
     * @param defaultContent generally the style associated to the Row. Can be retained or throwed to provide a custom logic also for css style.
     * @return decorated content for the TR tag, defaultContent in the default implementation
     */
    public String decorateRowTag(String defaultContent) {
        String param = buildParamString();

        String rt = " id=\"riga_" + getViewIndex() + "\" onClick=\"returnSelection(" + param + ")\"";
        rt += " onMouseOver=\"selectPopupRow(this)\"";
        rt += " onMouseOut=\"deselectPopupRow(this)\"";
        try {
            if (getViewIndex() % 2 == 0) {
                rt += " class=\"odd\" baseClass=\"odd\"";
            } else {
                rt += " class=\"even\" baseClass=\"even\"";
            }
            rt += " selClass=\"selectedPopup\"";
        } catch (Exception e) {
            e.printStackTrace();
        }

        return rt;
    }

    private String buildParamString() {
        CoreEntity p = (CoreEntity) getCurrentRowObject();

        String paramPropertyString = (String) getPageContext().getRequest().getAttribute("paramPropertyString");
        log.debug("paramPropertyString=" + paramPropertyString);

        String param = "";
        StringTokenizer st = new StringTokenizer(paramPropertyString, ",");
        while (st.hasMoreTokens()) {
            String appoParamProp = st.nextToken().trim();
            Object appoParam;
            try {
                log.debug("LookupUtil.getBeanProperty for property=" + appoParamProp);
                appoParam = LookupUtil.getBeanProperty(p, appoParamProp);
                log.debug("LookupUtil.getBeanProperty getting value=" + appoParam);
                if (appoParam != null) {
                    if (appoParam instanceof String) {
                        appoParam = normalizePart((String) appoParam, "'", "\\'");
                        appoParam = normalizePart((String) appoParam, "\"", "&#034;");
                        appoParam = normalizePart((String) appoParam, "\r", "\\r");
                        appoParam = normalizePart((String) appoParam, "\n", "\\n");
                    }
        //                appoParam = CompatibleUrlEncoder.encode(appoParam.toString(), null);
                    log.debug("LookupUtil.getBeanProperty getting encoded value=" + appoParam);
                } else {
                    appoParam = "";
                }

                param += "'" + appoParam + "'";
                if (st.hasMoreTokens()) param += ",";

            } catch (ObjectLookupException e) {
                log.error("Used paramPropertyString has invalid property " + appoParamProp + ". Property discarded !");
            }
        }
        return param;
    }

    /**
     * Method normalizePart.
     * @param message
     * @param part
     * @param add
     */
    public static String normalizePart(String message, String part, String add) {
        int pos=0;
        while (message.indexOf(part,pos) != -1) {
            pos = message.indexOf(part,pos);
            if (pos == 0)
                message = add + message.substring(pos + part.length());
            else
                   message = message.substring(0, pos) + add + message.substring(pos + part.length());
            pos += part.length()+1;
        }
        return message;
    }

    public void finish() {
        JspWriter out = getPageContext().getOut();
        try {
            out.write("");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
