/**
 * 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.renderkit.AjaxRendererUtils;
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.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 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());
            }
            
            if (AjaxRendererUtils.isAjaxRequest(context) && panel.getSwitchType().equals(UISimpleTogglePanel.AJAX_SWITCH_TYPE)) {
                AjaxRendererUtils.addRegionByName(context,
                        panel,
                        panel.getId());
            }

        }
        
        


    }

    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();
        //String userOnClick = (String)component.getAttributes().get("onclick");
        //if(userOnClick!=null) {
        //	onClick.append(userOnClick);
        //	if(!userOnClick.trim().endsWith(";")) {
        //		onClick.append("; ");
        //	}
        //}


        if (UISimpleTogglePanel.CLIENT_SWITCH_TYPE.equals(switchType)) {
            // Client
            String panelId = tgComp.getClientId(context);
            onClick.append("SimpleTogglePanelManager.toggleOnClient('")
                    .append(panelId)
                    .append("');");
        } else if (UISimpleTogglePanel.AJAX_SWITCH_TYPE.equals(switchType)) {
            // Ajax
            // writer.writeAttribute(HTML.onclick_ATTRIBUTE,AjaxRendererUtils.buildOnClick(tab,context),"ajaxOnclick");
            onClick.append(AjaxRendererUtils.buildOnClick(component, context));
            //return super.getOnClick(context, component);
        } else {
            // Server


            onClick.append("SimpleTogglePanelManager.toggleOnServer('")
                    .append(component.getClientId(context))
                    .append("'")


                    .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;
    }

}