/*
 * Copyright (c) 2006-2007, Dennis M. Sosnoski All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
 * following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
 * disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
 * following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of
 * JiBX nor the names of its contributors may be used to endorse or promote products derived from this software without
 * specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.jibx.schema.codegen.custom;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.jibx.schema.INamed;
import org.jibx.schema.elements.AnnotatedBase;
import org.jibx.schema.elements.AnnotationElement;
import org.jibx.schema.elements.DocumentationElement;
import org.jibx.schema.elements.SchemaBase;
import org.w3c.dom.Node;

/**
 * Wrapper for a schema definition component used in code generation. This provides some convenience methods, but also
 * gives the basis for schema code generation customizations. An instance is associated with each schema component which
 * contributes to the code generation, including attributes and elements as well as groupings including compositors, and
 * type definitions.
 * 
 * @author Dennis M. Sosnoski
 */
public class SchemaComponentWrapper
{
    private final SchemaBase m_schemaComponent;
    
    private ArrayList m_nestedComponents;
    
    /**
     * Constructor.
     * 
     * @param comp
     */
    public SchemaComponentWrapper(SchemaBase comp) {
        m_schemaComponent = comp;
    }
    
    /**
     * Get the name associated with this component.
     * 
     * @return name (<code>null</code> if none)
     */
    public String getSchemaName() {
        if (m_schemaComponent instanceof INamed) {
            return ((INamed)m_schemaComponent).getName();
        } else {
            throw new IllegalStateException("Component " + m_schemaComponent + " has no name");
        }
    }
    
    /**
     * Get the name of the schema element.
     * 
     * @return name
     */
    public String getSchemaForm() {
        return m_schemaComponent.name();
    }
    
    /**
     * Get JavaDocs for component. This just returns the XML text for the content of all <b>Documentation</b>
     * annotation items on the component.
     * 
     * @return documentation text
     */
    public String getJavaDocs() {
        if (m_schemaComponent instanceof AnnotatedBase) {
            AnnotationElement ann = ((AnnotatedBase)m_schemaComponent).getAnnotation();
            if (ann != null) {
                return elementListText(ann.getItemsList());
            }
        }
        return "";
    }
    
    /**
     * Extract documentation content from list of annotation items.
     * 
     * @param items annotation items
     * @return XML documentation text
     */
    private static String elementListText(List items) {
        try {
            
            // start by setting up the transform
            String text = null;
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            DOMSource source = new DOMSource();
            
            // loop through all annotation items
            for (Iterator iter = items.iterator(); iter.hasNext();) {
                Object item = iter.next();
                if (item instanceof DocumentationElement) {
                    
                    // accumulate XML text content of documentation elements
                    ArrayList contents = ((DocumentationElement)item).getContents();
                    StringWriter swrite = new StringWriter();
                    for (int i = 0; i < contents.size(); i++) {
                        source.setNode((Node)contents.get(i));
                        transformer.transform(source, new StreamResult(swrite));
                    }
                    if (text == null) {
                        text = " ";
                    }
                    text += swrite.toString();
                    
                }
            }
            return text;
            
        } catch (TransformerConfigurationException e) {
            throw new IllegalStateException("Unable to configure transform: " + e.getMessage());
        } catch (TransformerException e) {
            throw new IllegalStateException("Error in transform: " + e.getMessage());
        }
    }
}