/*
 * Copyright (c) 2007-2008, 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.ws.wsdl.tools.custom;

import java.util.List;

import org.apache.log4j.Logger;
import org.jibx.binding.classes.ClassItem;
import org.jibx.custom.classes.ClassCustom;
import org.jibx.custom.classes.CustomBase;
import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.JiBXException;
import org.jibx.runtime.impl.UnmarshallingContext;
import org.jibx.util.StringArray;

/**
 * Method parameter or return value customization information.
 * 
 * @author Dennis M. Sosnoski
 */
public class ValueCustom extends CustomBase
{
    /** Logger for class. */
    private static final Logger s_logger = Logger.getLogger(ValueCustom.class.getName());
    
    /** Enumeration of allowed attribute names */
    public static final StringArray s_allowedAttributes =
        new StringArray(new String[] { "element-name", "name", "required", "type" });
    
    // value customization information
    private boolean m_primitive; // internal use, not included in binding
    
    private String m_boundType; // internal use, not included in binding
    
    private String m_valueName;
    
    private String m_elementName;
    
    private String m_type;
    
    private String m_createType;
    
    private String m_factoryMethod;
    
    private Boolean m_required;
    
    private List m_documentation;
    
    /**
     * Constructor.
     * 
     * @param parent
     * @param name
     */
    protected ValueCustom(NestingBase parent, String name) {
        super(parent);
        m_valueName = name;
    }
    
    /**
     * Make sure all attributes are defined.
     * 
     * @param uctx unmarshalling context
     */
    private void preSet(IUnmarshallingContext uctx) {
        validateAttributes(uctx, s_allowedAttributes);
    }
    
    /**
     * Get value name.
     * 
     * @return name
     */
    public String getValueName() {
        return m_valueName;
    }
    
    /**
     * Get XML element name.
     * 
     * @return name
     */
    public String getElementName() {
        return m_elementName;
    }
    
    /**
     * Set XML element name.
     * 
     * @param name
     */
    public void setElementName(String name) {
        m_elementName = name;
    }
    
    /**
     * Get value type. This method should only be used after the {@link #complete(String, List, Boolean)} method is
     * called.
     * 
     * @return value type
     */
    public String getType() {
        return m_type;
    }
    
    /**
     * Get item type for parameterized list collection. This base class implementation always returns <code>null</code>.
     * 
     * @return <code>null</code>
     */
    public String getItemType() {
        return null;
    }
    
    /**
     * Get value type to be bound. This is the same as the plain value type for a simple (non-collection); for an array
     * value, it's just the array item type; and for a non-array collection it takes the same form as a generic type
     * declaration, with the actual item type enclosed in a less-than/greater-than sign pair following the base type.
     * 
     * @return parmaterized type
     */
    public String getBoundType() {
        return m_boundType;
    }
    
    /**
     * Get name for elements representing items in collection. This base class implementation always returns
     * <code>null</code>.
     * 
     * @return <code>null</code>
     */
    public String getItemElementName() {
        return null;
    }
    
    /**
     * Get member create type.
     * 
     * @return type used for creating new instance (<code>null</code> if none)
     */
    public String getCreateType() {
        return m_createType;
    }
    
    /**
     * Get factory method.
     * 
     * @return method used for creating new instance (<code>null</code> if none)
     */
    public String getFactoryMethod() {
        return m_factoryMethod;
    }
    
    /**
     * Check if value is required.
     * 
     * @return <code>true</code> if required, <code>false</code> if not
     */
    public boolean isRequired() {
        if (m_required == null) {
            if (m_primitive) {
                return getParent().isPrimitiveRequired(m_type);
            } else {
                return getParent().isObjectRequired(m_type);
            }
        } else {
            return m_required.booleanValue();
        }
    }
    
    /**
     * Get value documentation node list. This method should only be used after the
     * {@link #complete(String, List, Boolean)} method is called.
     * 
     * @return list of documentation nodes (<code>null</code> if none)
     */
    public List getDocumentation() {
        return m_documentation;
    }
    
    /**
     * Complete customization information based on supplied type. If the type information has not previously been set,
     * this will set it. It will also derive the appropriate XML name, if not previously set.
     * 
     * @param type (<code>null</code> if none available)
     * @param docs default documentation text (<code>null</code> if none)
     * @param req required member flag (<code>null</code> if unknown)
     */
    /* package */void complete(String type, List docs, Boolean req) {
        if (s_logger.isDebugEnabled()) {
            StringBuffer buff = new StringBuffer();
            if (m_valueName == null) {
                buff.append("Completing return value");
            } else {
                buff.append("Completing value ");
                buff.append(m_valueName);
            }
            buff.append(" with element name ");
            buff.append(m_elementName);
            s_logger.debug(buff.toString());
        }
        if (m_type == null) {
            if (type == null) {
                m_type = "java.lang.Object";
            } else {
                m_type = type;
            }
            s_logger.debug("Set type " + m_type);
        }
        m_primitive = ClassItem.isPrimitive(m_type);
        // TODO: check consistency of setting
        if (m_required == null) {
            m_required = req;
            s_logger.debug("Set required " + req);
        }
        if (m_documentation == null) {
            m_documentation = docs;
        }
        String itype = getItemType();
        if (itype == null) {
            if (type.endsWith("[]")) {
                m_boundType = type.substring(0, type.length() - 2);
            } else {
                m_boundType = type;
            }
        } else {
            m_boundType = type + '<' + itype + '>';
        }
        s_logger.debug("Set bound type " + m_boundType);
        if (!m_primitive && m_createType == null && m_factoryMethod == null) {
            ClassCustom cust = getGlobal().getClassCustomization(type);
            if (cust != null) {
                m_createType = cust.getCreateType();
                m_factoryMethod = cust.getFactoryMethod();
            }
        }
    }
    
    /**
     * Parameter value unmarshalling factory. This gets the containing element and the name so that the standard
     * constructor can be used.
     * 
     * @param ictx
     * @return created instance
     * @throws JiBXException
     */
    private static ValueCustom parameterFactory(IUnmarshallingContext ictx) throws JiBXException {
        String name = ((UnmarshallingContext)ictx).attributeText(null, "name");
        s_logger.debug("Creating parameter instance with name " + name);
        return new ValueCustom((OperationCustom)getContainingObject(ictx), name);
    }
    
    /**
     * Return value unmarshalling factory. This gets the containing element so that the standard constructor can be
     * used.
     * 
     * @param ictx
     * @return created instance
     */
    private static ValueCustom returnFactory(IUnmarshallingContext ictx) {
        return new ValueCustom((OperationCustom)getContainingObject(ictx), "return");
    }
    
    /**
     * Parameter value unmarshalling factory. This gets the containing element and the name so that the standard
     * constructor can be used.
     * 
     * @param ictx
     * @return created instance
     * @throws JiBXException
     */
    private static CollectionValueCustom collectionParameterFactory(IUnmarshallingContext ictx) throws JiBXException {
        String name = ((UnmarshallingContext)ictx).attributeText(null, "name");
        s_logger.debug("Creating collection parameter instance with name " + name);
        return new CollectionValueCustom((OperationCustom)getContainingObject(ictx), name);
    }
    
    /**
     * Return value unmarshalling factory. This gets the containing element so that the standard constructor can be
     * used.
     * 
     * @param ictx
     * @return created instance
     */
    private static CollectionValueCustom collectionReturnFactory(IUnmarshallingContext ictx) {
        return new CollectionValueCustom((OperationCustom)getContainingObject(ictx), "return");
    }
}