/**
 * 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
 */

/*
 * Created on 04.07.2006
 */
package org.richfaces.renderkit.html;

import org.ajax4jsf.component.AjaxSupport;
import org.ajax4jsf.javascript.JSFunction;
import org.ajax4jsf.javascript.JSFunctionDefinition;
import org.ajax4jsf.javascript.JSReference;
import org.ajax4jsf.renderkit.AjaxRendererUtils;
import org.ajax4jsf.renderkit.RendererUtils;
import org.ajax4jsf.renderkit.RendererUtils.HTML;
import org.richfaces.component.UISimpleTogglePanel;
import org.richfaces.event.SimpleToggleEvent;

import javax.faces.component.UIComponent;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.event.ActionEvent;
import javax.faces.event.PhaseId;
import java.io.IOException;
import java.util.Map;

//public class SimpleTogglePanelRenderer extends AjaxCommandLinkRenderer {

public class SimpleTogglePanelRenderer extends org.ajax4jsf.renderkit.HeaderResourcesRendererBase {
    //XXXX by nick - denis - seems there is a lot of code common to org.richfaces.renderkit.html.ToggleControlRenderer. Please commonize!
    //private InternetResource[] _scripts = {new PrototypeScript(), getResource("scripts/simpleTogglePanel.js") };

    final static String NONE = "none";
    final static String EMPTY = "";
    
    protected Class getComponentClass() {
        return UISimpleTogglePanel.class;
    }

    //XXXX by nick - denis - move scripts to template
    //protected InternetResource[] getAdditionalScripts() {
    //	return _scripts;
    //}


    public boolean getRendersChildren() {
        return true;
    }

	public void writeEventHandlerFunction(FacesContext context,
			UIComponent component, String eventName) throws IOException {
		RendererUtils.writeEventHandlerFunction(context, component, eventName);
	}
        
    public void doDecode(FacesContext context, UIComponent component) {

        super.doDecode(context, component);


        ExternalContext exCtx = context.getExternalContext();

        Map rqMap = exCtx.getRequestParameterMap();
        Object clnId = rqMap.get(component.getClientId(context));
        UISimpleTogglePanel panel = (UISimpleTogglePanel) component;

        if (clnId != null) {
            // enqueue event here for this component or for component with Id
            // taken fro forId attribute
            
            String switchType = panel.getSwitchType();
            if (!(UISimpleTogglePanel.CLIENT_SWITCH_TYPE.equals(switchType))) {

                //xxxx by nick - denis - use constants, please!
                if ((panel.isOpened() == UISimpleTogglePanel.EXPANDED)) {
                    panel.setOpened(UISimpleTogglePanel.COLLAPSED);
                } else {
                    //xxxx by nick - denis - use constants, please!
                    panel.setOpened(UISimpleTogglePanel.EXPANDED);
                }
                SimpleToggleEvent event = new SimpleToggleEvent(panel, (panel.isOpened()));
                if (panel.isImmediate()) {
                    event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
                } else {
                    event.setPhaseId(PhaseId.INVOKE_APPLICATION);
                }
                event.queue();
                
            } else {
                if (panel.isOpened()!= new Boolean((String) clnId).booleanValue()){
                	panel.setAjaxSingle(false);
                    SimpleToggleEvent event = new SimpleToggleEvent(panel, (panel.isOpened()));
                    if (panel.isImmediate()) {
                        event.setPhaseId(PhaseId.APPLY_REQUEST_VALUES);
                    } else {
                        event.setPhaseId(PhaseId.INVOKE_APPLICATION);
                    }
                    event.queue();
                }
                if (null == panel.getValueBinding("value"))
                	panel.setOpened(new Boolean((String) clnId).booleanValue());
            }
            
            // in case of "ajax" request and "ajax" switch mode of toggle panel
            // set the regions to be rendered (reRendered) after operating this "ajax" request
            if (AjaxRendererUtils.isAjaxRequest(context) && panel.getSwitchType().equals(UISimpleTogglePanel.AJAX_SWITCH_TYPE)) {
                // add toggle panel itself to rendered list of components
        	AjaxRendererUtils.addRegionByName(context,
                        panel,
                        panel.getId());
        	// add regions specified in the "reRender" attribute of toggle panel
        	// to rendered list of components
                AjaxRendererUtils.addRegionsFromComponent(panel, context);
            }

        }
    }

    public String getdivdisplay(FacesContext context, UIComponent component) {

        String Switch = Boolean.toString(((UISimpleTogglePanel) component).isOpened());
        if (Switch == null || Switch.equals(Boolean.toString(UISimpleTogglePanel.EXPANDED)))
        {
            //xxxx by nick - denis - do not set "block" explicitly - that can break some elements, set "" for display. See Element.show() in prototype.js
            return "";
        }
        return "none";
    }

    public String getOnClick(FacesContext context, UIComponent component) {
        UISimpleTogglePanel tgComp = (UISimpleTogglePanel) component;

        String switchType = tgComp.getSwitchType();
        StringBuffer onClick = new StringBuffer();
    	JSReference eventRef = new JSReference("event");
    	String panelId = tgComp.getClientId(context);

	if (UISimpleTogglePanel.CLIENT_SWITCH_TYPE.equals(switchType)) {
            // Client
            JSFunction function = new JSFunction("SimpleTogglePanelManager.toggleOnClient");
            function.addParameter(eventRef);
            function.addParameter(panelId);
            function.appendScript(onClick);
            onClick.append(";");
            
        } else if (UISimpleTogglePanel.AJAX_SWITCH_TYPE.equals(switchType)) {
//			Ajax
                 	
        	JSFunction function = new JSFunction("SimpleTogglePanelManager.toggleOnAjax");
        	function.addParameter(eventRef);
        	function.addParameter(panelId);
        	function.appendScript(onClick);
        	onClick.append(";");
        
        	JSFunction ajaxFunction = AjaxRendererUtils.buildAjaxFunction(tgComp, context);
        	ajaxFunction.addParameter(AjaxRendererUtils.buildEventOptions(context, tgComp));
           	ajaxFunction.appendScript(onClick);
           	
           	if (tgComp instanceof AjaxSupport) {
    			AjaxSupport support = (AjaxSupport) tgComp;
    			if (support.isDisableDefault()) {
    				onClick.append("; return false;");
    			}
    		}

        } else {
            // Server
        	JSFunction function = new JSFunction("SimpleTogglePanelManager.toggleOnServer");	
            function.addParameter(eventRef);
            function.addParameter(panelId);
            function.appendScript(onClick);
            onClick.append(";");        
            //.append(tgComp.getSwitch()==null?"'0'":"'" + tgComp.getSwitch() + "'")
            //.append("")
        }
        return onClick.toString();
    }

    protected String getValueAsString(FacesContext context, UISimpleTogglePanel Panel) {
        return getUtils().getValueAsString(context, Panel);
    }

    public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
        // TODO Auto-generated method stub
        UISimpleTogglePanel comp = (UISimpleTogglePanel) component;
        //xxxx by nick - denis - use constants, please!
        if (!(((comp.getSwitchType() == null) || (comp.getSwitchType().equals(UISimpleTogglePanel.CLIENT_SWITCH_TYPE) != true)) && (comp.isOpened() == UISimpleTogglePanel.COLLAPSED)))
        {
            super.encodeChildren(context, component);
        }
    }
    
    public String getSwitchOnStatus(FacesContext context, UIComponent component) {
        String sw = Boolean.toString(((UISimpleTogglePanel) component).isOpened());
        if (sw == null || sw.equals(Boolean.toString(UISimpleTogglePanel.EXPANDED)))
            return EMPTY; 
        else return NONE;
    }

    public String getSwitchOffStatus(FacesContext context, UIComponent component) {
        String sw = Boolean.toString(((UISimpleTogglePanel) component).isOpened());
        if (sw == null || sw.equals(Boolean.toString(UISimpleTogglePanel.EXPANDED)))
            return NONE; 
        else return EMPTY;
    }

}