/**
 * License Agreement.
 *
 *  JBoss RichFaces - Ajax4jsf Component Library
 *
 * Copyright (C) 2007  Exadel, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License version 2.1 as published by the Free Software Foundation.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */

package org.richfaces.renderkit;

import org.ajax4jsf.util.SelectUtils;
import org.richfaces.component.UIDataFltrSlider;
import org.richfaces.event.DataFilterSliderEvent;

import javax.faces.component.UIComponent;
import javax.faces.component.UIForm;
import javax.faces.component.UIInput;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.convert.ConverterException;
import java.io.IOException;
import java.util.Map;

/**
 * @author Wesley Hales
 */
public class DataFilterSliderRendererBase extends org.ajax4jsf.renderkit.HeaderResourcesRendererBase {

    protected Class getComponentClass() {
        return UIDataFltrSlider.class;
    }

    public Object getConvertedValue(FacesContext context, UIComponent component, Object submittedValue) throws ConverterException {
        return SelectUtils.getConvertedUIInputValue(context, (UIInput) component, (String) submittedValue);
    }

    public Map getRequestMap() {
        return FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
    }

    public String renderSliderJs1(FacesContext context, UIDataFltrSlider slider) throws IOException {
	
	String clientId = slider.getClientId(context);

        String sliderScript = "var dataFilterSlider = new Control.Slider('"+ clientId +"slider-handle', '"+ clientId +"slider-track', {\n" +
                                                                        "range: $R(" + slider.getStartRange() + "," + slider.getEndRange() + "),\n" +
                                                                        "values: [" + slider.getSliderRange() + "],\n" +
                                                                        "startSpan: '"+ clientId +"slider-trailer',\n" +
                                                                        "sliderValue:$('"+ clientId +"slider_val').value";

        if (slider.isOnSlide()) {
            sliderScript = sliderScript +
                    ",\nonSlide: function(v) { updateSlider1(v);}";
        }

        if (slider.isOnChange()) {
            sliderScript = sliderScript +
                    ",\nonChange: function(v) { updateSlider1(v);}\n";
        }

        sliderScript = sliderScript + "            });\n";

        return sliderScript;
    }

    public String renderSliderJs2(FacesContext context, UIDataFltrSlider slider) throws IOException {

	String clientId = slider.getClientId(context);
	
	String formClientId = _findFormClientId(context, slider);

        String sliderClientId = slider.getClientId(context);

        String id = slider.getId();

        String sliderHandlerScript = "function updateSlider1(value) {\n" +
                                                "$('"+ clientId +"slider_val').value = value;\n" +
                                                "try{\n" +
                                                "eval(document.forms['" + formClientId + "'].action);\n" +
                                                "}catch(exception){\n" +
                                                "}\n" +
                                                "}\n";

        return sliderHandlerScript;
    }

    /**
     * Finds the parent UIForm component client identifier.
     *
     * @param context   the Faces context
     * @param component the Faces component
     * @return the parent UIForm client identifier, if present, otherwise null
     */
    private String _findFormClientId(
            FacesContext context,
            UIComponent component) {
        while (component != null &&
                !(component instanceof UIForm)) {
            component = component.getParent();
        }

        return (component != null) ? component.getClientId(context) : null;
    }

    protected void doDecode(FacesContext context, UIComponent component) {

        ExternalContext external = context.getExternalContext();
        Map requestParams = external.getRequestParameterMap();
        String clientId = component.getClientId(context);

        UIDataFltrSlider dataFilterSlider = (UIDataFltrSlider) component;
        Integer oldSliderVal = dataFilterSlider.getHandleValue();
        //Here we get new slider val and compare with old value
        Integer newSliderVal = dataFilterSlider.getStartRange();

        if (requestParams.get(clientId + "slider_val") != null
                && !"".equals(requestParams.get(clientId + "slider_val"))) {
            newSliderVal = Integer.valueOf(requestParams.get(clientId + "slider_val").toString());
        }

        if (newSliderVal.equals(oldSliderVal)) {
            //you could use this to reset the table, but it gets called when the dataScroller is clicked also
            //The only way I know to reset the table is to find the component and use helper to reset in an actionListener
            //ajaxSlider.resetDataTable();
            //ajaxSlider.setHandleValue(ajaxSlider.getStartRange());
        } else {
            dataFilterSlider.setHandleValue(newSliderVal);
            DataFilterSliderEvent event = new DataFilterSliderEvent(dataFilterSlider, oldSliderVal, newSliderVal);
            //dataFilterSlider.queueEvent(event);
            event.queue();
            if (dataFilterSlider.isStoreResults()) {
                dataFilterSlider.filterDataTable(newSliderVal.intValue());
            }

        }
    }

    public void encodeChildren(FacesContext context,
                               UIComponent component) throws IOException {

        component.encodeBegin(context);
        if (component.getChildCount() > 0) {

            if (component.getRendersChildren()) {
                component.encodeChildren(context);
            }
            component.encodeEnd(context);

        }
    }

    protected boolean attributeToBoolean(UIComponent component, String attributeName) {
        Object object = component.getAttributes().get(attributeName);
        if (object instanceof Boolean) {
            return ((Boolean) object).booleanValue();
        }

        if (object instanceof String) {
            return new Boolean((String) object).booleanValue();
        }

        return object != null && object.equals(Boolean.TRUE);
    }

}
