/*
 * ICESOFT COMMERCIAL SOURCE CODE LICENSE V 1.1
 *
 * The contents of this file are subject to the ICEsoft Commercial Source
 * Code License Agreement V1.1 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the
 * License at
 * http://www.icesoft.com/license/commercial-source-v1.1.html
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under
 * the License.
 *
 * Copyright 2009-2015 ICEsoft Technologies Canada, Corp. All Rights Reserved.
 */

package com.icesoft.components.accessible.panelconfirmation;

import com.icesoft.faces.renderkit.dom_html_basic.DomBasicRenderer;
import com.icesoft.faces.component.ExtendedAttributeConstants;
import com.icesoft.faces.component.ext.renderkit.FormRenderer;
import com.icesoft.faces.component.util.CustomComponentUtils;

import com.icesoft.faces.renderkit.dom_html_basic.HTML;
import com.icesoft.faces.context.DOMContext;
import com.icesoft.faces.util.CoreUtils;

import javax.faces.context.FacesContext;
import javax.faces.component.UICommand;
import javax.faces.component.UIComponent;
import javax.faces.event.ActionEvent;

import org.w3c.dom.Element;
import org.w3c.dom.Text;

import java.io.IOException;
import java.util.Map;

import com.icesoft.util.pooling.ClientIdPool;
import com.icesoft.components.accessible.util.CoreComponentUtils;

public class PanelConfirmationRenderer extends DomBasicRenderer {

    // everything is excluded
    private static final String[] PASSTHRU_EXCLUDE = new String[]{ HTML.STYLE_ATTR, HTML.TITLE_ATTR };
    private static final String[] PASSTHRU = ExtendedAttributeConstants.getAttributes(
            ExtendedAttributeConstants.ICE_PANELCONFIRMATION, PASSTHRU_EXCLUDE);
    
    public void encodeBegin(FacesContext facesContext, UIComponent uiComponent)
            throws IOException {
    }
    
    public boolean getRendersChildren() {
        return false;
    }
    
    public void encodeChildren(FacesContext facescontext,
                               UIComponent uicomponent) throws IOException {
    }
    
    public void encodeEnd(FacesContext facesContext, UIComponent uiComponent) throws IOException {
    
        validateParameters(facesContext, uiComponent, null);
        
        PanelConfirmation panelConfirmation = (PanelConfirmation) uiComponent;
        
        DOMContext domContext = DOMContext.attachDOMContext(facesContext, uiComponent);
        
        Element rootDiv;
        if (domContext.isInitialized()) {
            rootDiv = (Element) domContext.getRootNode();
        } else {
            rootDiv = domContext.createRootElement(HTML.DIV_ELEM);
        }
        
        String id = panelConfirmation.getClientId(facesContext);
        
        rootDiv.setAttribute(HTML.ID_ATTR, id);
        rootDiv.setAttribute(HTML.CLASS_ATTR, panelConfirmation.getStyleClass());
        String style = panelConfirmation.getStyle();
        if (CoreComponentUtils.isJavaScriptDisabled(facesContext) &&
        		panelConfirmation.isShowWhenJSDisable()) {
                rootDiv.setAttribute(HTML.CLASS_ATTR, panelConfirmation.getStyleClass() + " iceJSDISPnlCnf");
         } else {
            if (style != null) {
                rootDiv.setAttribute(HTML.STYLE_ATTR, style + "display: none;");
            } else {
                rootDiv.setAttribute(HTML.STYLE_ATTR, "display: none;");
            }
        }


        
        Element rootDiv2 = domContext.createElement(HTML.DIV_ELEM);
        rootDiv2.setAttribute(HTML.WIDTH_ATTR, "100%");
        rootDiv.appendChild(rootDiv2);
        
        // Header
        Element headerDiv = domContext.createElement(HTML.DIV_ELEM);
        headerDiv.setAttribute(HTML.ID_ATTR, ClientIdPool.get(id + "-handle"));
        headerDiv.setAttribute(HTML.CLASS_ATTR, panelConfirmation.getHeaderClass());
        rootDiv2.appendChild(headerDiv);
        
        String title = panelConfirmation.getTitle();
        if (title == null) {
            title = "Confirm";
        }
        if (title.equals("")) {
            title = "Confirm";
        }
        Element titleSpan = domContext.createElement(HTML.SPAN_ELEM);
        titleSpan.setAttribute(HTML.ID_ATTR, ClientIdPool.get(id + "-title"));
        headerDiv.appendChild(titleSpan);
        Text titleText = domContext.createTextNode(title);
        titleSpan.appendChild(titleText);
        
        // Body
        Element bodyDiv = domContext.createElement(HTML.DIV_ELEM);
        bodyDiv.setAttribute(HTML.ID_ATTR, ClientIdPool.get(id + "-message"));
        bodyDiv.setAttribute(HTML.CLASS_ATTR, panelConfirmation.getBodyClass());
        rootDiv2.appendChild(bodyDiv);
        
        String message = panelConfirmation.getMessage();
        if (message == null) {
            message = "";
        }
        Element messageSpan = domContext.createElement(HTML.SPAN_ELEM);
        bodyDiv.appendChild(messageSpan);
        Text messageText = domContext.createTextNode(message);
        messageSpan.appendChild(messageText);
        
        // Buttons
        Element buttonsDiv = domContext.createElement(HTML.DIV_ELEM);
        buttonsDiv.setAttribute(HTML.CLASS_ATTR, panelConfirmation.getButtonsClass());
        rootDiv2.appendChild(buttonsDiv);
        
        String type = panelConfirmation.getType();
        if (type != null) {
            if (type.equalsIgnoreCase("acceptOnly")) {
                renderAcceptButton(panelConfirmation, domContext, id, buttonsDiv);
            } else if (type.equalsIgnoreCase("cancelOnly")) {
                renderCancelButton(panelConfirmation, domContext, id, buttonsDiv);
            } else {
                renderAcceptButton(panelConfirmation, domContext, id, buttonsDiv);
                renderCancelButton(panelConfirmation, domContext, id, buttonsDiv);
            }
        } else {
            renderAcceptButton(panelConfirmation, domContext, id, buttonsDiv);
            renderCancelButton(panelConfirmation, domContext, id, buttonsDiv);
        }
        
        if (panelConfirmation.isDraggable()) {
            Element clientOnly = domContext.createElement(HTML.INPUT_ELEM);
	        clientOnly.setAttribute(HTML.TYPE_ATTR, "hidden");
	        clientOnly.setAttribute(HTML.ID_ATTR, id + "clientOnly");
	        rootDiv.appendChild(clientOnly);
        }
        
        FormRenderer.addHiddenField(facesContext, uiComponent.getClientId());
        
        domContext.stepOver();
    }
    
    public void decode(FacesContext facesContext, UIComponent uiComponent) {
    	if (CoreComponentUtils.isJavaScriptDisabled(facesContext)) {
	        Map requestParameterMap = facesContext.getExternalContext().getRequestParameterMap();
	        String componentClientId = uiComponent.getClientId(facesContext);
	        if (requestParameterMap.containsKey(componentClientId+ "-accept")) {
	        	if (uiComponent.getAttributes().containsKey("owner")) {
	        		String buttonId = String.valueOf(uiComponent.getAttributes().get("owner"));
	            	UICommand button = (UICommand) CoreComponentUtils.findComponent(buttonId, 
	            						uiComponent);
	            	button.queueEvent(new ActionEvent(button));
	
	        	}
	        } 
    	}
        
    }
    
    public void renderAcceptButton(PanelConfirmation panelConfirmation, DOMContext domContext, String id, Element td) {
    
        String acceptLabel = panelConfirmation.getAcceptLabel();
        if (acceptLabel == null) {
            acceptLabel = "Accept";
        }
        if (acceptLabel.equals("")) {
            acceptLabel = "Accept";
        }
        Element acceptButton = domContext.createElement(HTML.INPUT_ELEM);
        acceptButton.setAttribute(HTML.VALUE_ATTR, acceptLabel);
        acceptButton.setAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_SUBMIT);
        acceptButton.setAttribute(HTML.ID_ATTR, ClientIdPool.get(id + "-accept"));
        acceptButton.setAttribute(HTML.NAME_ATTR, ClientIdPool.get(id + "-accept"));
//        acceptButton.setAttribute(HTML.ONCLICK_ATTR, "Ice.PanelConfirmation.current.accept();return false;");
        td.appendChild(acceptButton);
    }
    
    public void renderCancelButton(PanelConfirmation panelConfirmation, DOMContext domContext, String id, Element td) {
    
        String cancelLabel = panelConfirmation.getCancelLabel();
        if (cancelLabel == null) {
            cancelLabel = "Cancel";
        }
        if (cancelLabel.equals("")) {
            cancelLabel = "Cancel";
        }
        Element cancelButton = domContext.createElement(HTML.INPUT_ELEM);
        cancelButton.setAttribute(HTML.VALUE_ATTR, cancelLabel);
        cancelButton.setAttribute(HTML.TYPE_ATTR, HTML.INPUT_TYPE_SUBMIT);
        cancelButton.setAttribute(HTML.ID_ATTR, ClientIdPool.get(id + "-cancel"));
        cancelButton.setAttribute(HTML.NAME_ATTR, ClientIdPool.get(id + "-cancel"));
//        cancelButton.setAttribute(HTML.ONCLICK_ATTR, "Ice.PanelConfirmation.current.cancel();return false;");
        td.appendChild(cancelButton);
    }
    
    public static String renderOnClickString(UIComponent uiComponent, String originalOnClick) {
        String panelConfirmationId = String.valueOf(uiComponent.getAttributes().get("panelConfirmation"));
        PanelConfirmation panelConfirmation = (PanelConfirmation) CoreComponentUtils
                .findComponent(panelConfirmationId, uiComponent);
        if (panelConfirmation != null) {
        	panelConfirmation.getAttributes().put("owner", uiComponent.getId());
        	if (CoreComponentUtils.isJavaScriptDisabled(FacesContext.getCurrentInstance())) {
        		return "";
        	}
        	FacesContext facesContext = FacesContext.getCurrentInstance();
            panelConfirmationId = panelConfirmation.getClientId(facesContext);
            String autoCentre = panelConfirmation.isAutoCentre() ? "true" : "false";
            String draggable = panelConfirmation.isDraggable() ? "true" : "false";
            String displayAtMouse = panelConfirmation.isDisplayAtMouse() ? "true" : "false";
            return "new Ice.PanelConfirmation(this,event,'" + panelConfirmationId + "',"
                + autoCentre + "," + draggable + "," + displayAtMouse + ","
                + "'" + CoreUtils.resolveResourceURL(facesContext,"/xmlhttp/blank") + "',"
                + "function(event){" + originalOnClick + "});return false;";
        } else {
            return originalOnClick;
        }
    }
}
