/*
 * 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.faces.impl.renderkit.xhtml;

import javax.el.ValueExpression;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.component.UIComponent;
import javax.faces.render.Renderer;
import java.io.IOException;
import java.util.Map;

public abstract class XhtmlRendererBase extends Renderer {
    protected abstract String getTagName();

    @Override
    public void encodeBegin(FacesContext context, UIComponent component)
            throws IOException {
        String parentId = component.getParent().getClientId();
        ResponseWriter writer = context.getResponseWriter();
        writer.startElement(getTagName(), component);
        if( component.getId() != null && component.getId().length() > 0 ){
            writer.writeAttribute("id", component.getClientId(), "id");
        }
        Map<String, Object> attrMap = component.getAttributes();
        for (String name : attrMap.keySet())  {
            if (name.startsWith("javax.faces") || 
                name.startsWith("com.sun") ||
                "".equals(name))  {
                continue;
            }
            writer.writeAttribute("styleClass".equalsIgnoreCase(name) ? "class" : name, attrMap.get(name), null);
        }
        XhtmlComponent xhtmlComp = (XhtmlComponent) component;
        for (String name : xhtmlComp.getValueExpressions()) {
            ValueExpression ve = component.getValueExpression(name);
            if (ve != null) {
                Object value = ve.getValue(context.getELContext());
                writer.writeAttribute(name, value, null);
            }
        }
    }

    public void encodeEnd(FacesContext context, UIComponent component)
            throws IOException {
        ResponseWriter writer = context.getResponseWriter();
        writer.endElement(getTagName());
    }
}
