/*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the License).  You may not use this file except in
* compliance with the License.
*
* You can obtain a copy of the license at
* https://glassfish.dev.java.net/public/CDDLv1.0.html or
* glassfish/bootstrap/legal/CDDLv1.0.txt.
* See the License for the specific language governing
* permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* Header Notice in each file and include the License file
* at glassfish/bootstrap/legal/CDDLv1.0.txt.
* If applicable, add the following below the CDDL Header,
* with the fields enclosed by brackets [] replaced by
* you own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Copyright (c) Ericsson AB, 2004-2007. All rights reserved.
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*/
package org.jvnet.glassfish.comms.deployment.runtime.sip;

import com.sun.enterprise.deployment.Application;
import com.sun.enterprise.deployment.Descriptor;
import com.sun.enterprise.deployment.Group;
import com.sun.enterprise.deployment.JmsDestinationReferenceDescriptor;
import com.sun.enterprise.deployment.ResourcePrincipal;
import com.sun.enterprise.deployment.ResourceReferenceDescriptor;
import com.sun.enterprise.deployment.Role;
import com.sun.enterprise.deployment.ServiceReferenceDescriptor;
import com.sun.enterprise.deployment.WritableJndiNameEnvironment;
import com.sun.enterprise.deployment.interfaces.SecurityRoleMapper;
import com.sun.enterprise.deployment.io.ConfigurationDeploymentDescriptorFile;
import com.sun.enterprise.deployment.node.ServiceReferenceNode;
import com.sun.enterprise.deployment.node.XMLElement;
import com.sun.enterprise.deployment.node.XMLElement;
import com.sun.enterprise.deployment.node.runtime.*;
import com.sun.enterprise.deployment.node.runtime.RuntimeDescriptorNode;
import com.sun.enterprise.deployment.node.runtime.common.EjbRefNode;
import com.sun.enterprise.deployment.node.runtime.common.ResourceEnvRefNode;
import com.sun.enterprise.deployment.node.runtime.common.ResourceRefNode;
import com.sun.enterprise.deployment.node.runtime.common.SecurityRoleMappingNode;
import com.sun.enterprise.deployment.node.runtime.web.*;
import com.sun.enterprise.deployment.runtime.RuntimeDescriptor;
import com.sun.enterprise.deployment.runtime.common.DefaultResourcePrincipal;
import com.sun.enterprise.deployment.runtime.common.EjbRef;
import com.sun.enterprise.deployment.runtime.common.PrincipalNameDescriptor;
import com.sun.enterprise.deployment.runtime.common.ResourceEnvRef;
import com.sun.enterprise.deployment.runtime.common.ResourceRef;
import com.sun.enterprise.deployment.runtime.common.SecurityRoleMapping;
import com.sun.enterprise.deployment.runtime.web.ClassLoader;
import com.sun.enterprise.deployment.types.EjbReference;
import com.sun.enterprise.deployment.util.DOLUtils;
import com.sun.enterprise.deployment.xml.ApplicationTagNames;
import com.sun.enterprise.deployment.xml.RuntimeTagNames;
import com.sun.enterprise.deployment.xml.RuntimeTagNames;
import com.sun.enterprise.deployment.xml.WebServicesTagNames;

import org.jvnet.glassfish.comms.deployment.backend.DeploymentConstants;
import org.jvnet.glassfish.comms.deployment.backend.SipBundleDescriptor;
import org.jvnet.glassfish.comms.deployment.backend.SipDTDRegistry;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

import org.xml.sax.Attributes;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 *
 * @author  Prasad Subramanian
 */
public class SipBundleRuntimeNode extends RuntimeBundleNode {
    SipBundleDescriptor descriptor = null;

    /** Creates new SipBundleRuntimeNode */
    public SipBundleRuntimeNode(SipBundleDescriptor descriptor) {
        super(descriptor);
        this.descriptor = descriptor;
        getDescriptor();
    }

    /** Creates new SipBundleRuntimeNode */
    public SipBundleRuntimeNode() {
        super(null);
    }

    /**
     * Initialize the child handlers
     */
    public void Init() {
        // we do not care about our standard DDS handles
        handlers = null;

        registerElementHandler(new XMLElement(
                RuntimeTagNames.SECURITY_ROLE_MAPPING),
            SecurityRoleMappingNode.class);
        registerElementHandler(new XMLElement(RuntimeTagNames.SESSION_CONFIG),
            SessionConfigNode.class, "setSessionConfig");
        registerElementHandler(new XMLElement(
                RuntimeTagNames.RESOURCE_ENV_REFERENCE),
            ResourceEnvRefNode.class);
        registerElementHandler(new XMLElement(
                RuntimeTagNames.MESSAGE_DESTINATION_REFERENCE),
            MessageDestinationRefNode.class);

        registerElementHandler(new XMLElement(
                RuntimeTagNames.RESOURCE_REFERENCE), ResourceRefNode.class);
        registerElementHandler(new XMLElement(RuntimeTagNames.EJB_REFERENCE),
            EjbRefNode.class);

        registerElementHandler(new XMLElement(RuntimeTagNames.CACHE),
            CacheNode.class, "setCache");

        registerElementHandler(new XMLElement(RuntimeTagNames.CLASS_LOADER),
            ClassLoaderNode.class, "setClassLoader");

        registerElementHandler(new XMLElement(
                RuntimeTagNames.LOCALE_CHARSET_INFO),
            LocaleCharsetInfoNode.class, "setLocaleCharsetInfo");

        registerElementHandler(new XMLElement(RuntimeTagNames.PROPERTY),
            WebPropertyContainerNode.class, "addWebProperty");

        registerElementHandler(new XMLElement(WebServicesTagNames.SERVICE_REF),
            ServiceRefNode.class);
        registerElementHandler(new XMLElement(
                RuntimeTagNames.MESSAGE_DESTINATION),
            MessageDestinationRuntimeNode.class);
        registerElementHandler(new XMLElement(WebServicesTagNames.WEB_SERVICE),
            WebServiceRuntimeNode.class);
    }

    /**
     * @return the XML tag associated with this XMLNode
     */
    protected XMLElement getXMLRootTag() {
        return new XMLElement(DeploymentConstants.SCAS_SIP_RUNTIME_TAG);
    }

    /**
     * @return the DOCTYPE that should be written to the XML file
     */
    public String getDocType() {
        return SipDTDRegistry.SUN_SIPAPP_110_DTD_PUBLIC_ID;
    }

    /**
     * @return the SystemID of the XML file
     */
    public String getSystemID() {
        return SipDTDRegistry.SUN_SIPAPP_110_DTD_SYSTEM_ID;
    }

    /**
     * @return NULL for all runtime nodes.
     */
    public List<String> getSystemIDs() {
        return null;
    }

    /**
     * register this node as a root node capable of loading entire DD files
     *
     * @param publicIDToDTD is a mapping between xml Public-ID to DTD
     * @return the doctype tag name
     */
    public static String registerBundle(Map publicIDToDTD) {
        publicIDToDTD.put(SipDTDRegistry.SUN_SIPAPP_110_DTD_PUBLIC_ID,
            SipDTDRegistry.SUN_SIPAPP_110_DTD_SYSTEM_ID);

        return DeploymentConstants.SCAS_SIP_RUNTIME_TAG;
    }

    /**
     * @return the descriptor instance to associate with this XMLNode
     */
    public Object getDescriptor() {
        return descriptor.getSunSipDescriptor();
    }

    /**
    * @return the web bundle descriptor instance to associate with this XMLNode
    */
    public SipBundleDescriptor getSipBundleDescriptor() {
        return descriptor;
    }

    /**
     * Adds  a new DOL descriptor instance to the descriptor instance associated with
     * this XMLNode
     *
     * @param descriptor the new descriptor
     */
    public void addDescriptor(Object newDescriptor) {
        if (newDescriptor instanceof EjbRef) {
            EjbRef ejbRef = (EjbRef) newDescriptor;
            descriptor.getSunSipDescriptor().addEjbRef(ejbRef);

            try {
                EjbReference ref = descriptor.getEjbReference(ejbRef.getEjbRefName());
                ref.setJndiName(ejbRef.getJndiName());
            } catch (IllegalArgumentException iae) {
                DOLUtils.getDefaultLogger().warning(iae.getMessage());
            }
        } else if (newDescriptor instanceof ResourceRef) {
            ResourceRef resourceRef = (ResourceRef) newDescriptor;
            descriptor.getSunSipDescriptor().addResourceRef(resourceRef);

            try {
                ResourceReferenceDescriptor rrd = descriptor.getResourceReferenceByName(resourceRef.getResRefName());
                rrd.setJndiName(resourceRef.getJndiName());

                DefaultResourcePrincipal drp = resourceRef.getDefaultResourcePrincipal();

                if (drp != null) {
                    ResourcePrincipal rp = new ResourcePrincipal(drp.getName(),
                            drp.getPassword());
                    rrd.setResourcePrincipal(rp);
                }
            } catch (IllegalArgumentException iae) {
                DOLUtils.getDefaultLogger().warning(iae.getMessage());
            }
        } else if (newDescriptor instanceof ResourceEnvRef) {
            ResourceEnvRef resourceEnvRef = (ResourceEnvRef) newDescriptor;
            descriptor.getSunSipDescriptor().addResourceEnvRef(resourceEnvRef);

            try {
                JmsDestinationReferenceDescriptor rrd = descriptor.getJmsDestinationReferenceByName(resourceEnvRef.getResourceEnvRefName());
                rrd.setJndiName(resourceEnvRef.getJndiName());
            } catch (IllegalArgumentException iae) {
                DOLUtils.getDefaultLogger().warning(iae.getMessage());
            }
        } else if (newDescriptor instanceof ServiceReferenceDescriptor) {
            descriptor.addServiceReferenceDescriptor((ServiceReferenceDescriptor) newDescriptor);
        } else if (newDescriptor instanceof SecurityRoleMapping) {
            SecurityRoleMapping srm = (SecurityRoleMapping) newDescriptor;
            descriptor.getSunSipDescriptor().addSecurityRoleMapping(srm);

            // store it in the application using pure DOL descriptors...
            Application app = descriptor.getApplication();

            if (app != null) {
                Role role = new Role(srm.getRoleName());
                SecurityRoleMapper rm = app.getRoleMapper();

                if (rm != null) {
                    List<PrincipalNameDescriptor> principals = srm.getPrincipalNames();

                    for (int i = 0; i < principals.size(); i++) {
                        rm.assignRole(principals.get(i).getPrincipal(), role,
                            descriptor);
                    }

                    List<String> groups = srm.getGroupNames();

                    for (int i = 0; i < groups.size(); i++) {
                        rm.assignRole(new Group(groups.get(i)), role, descriptor);
                    }
                }
            }
        } else {
            super.addDescriptor(descriptor);
        }
    }

    public void startElement(XMLElement element, Attributes attributes) {
        if (element.getQName().equals(RuntimeTagNames.PARAMETER_ENCODING)) {
            SunSipApp sunSipApp = (SunSipApp) getDescriptor();
            sunSipApp.setParameterEncoding(true);

            for (int i = 0; i < attributes.getLength(); i++) {
                if (RuntimeTagNames.DEFAULT_CHARSET.equals(attributes.getQName(
                                i))) {
                    sunSipApp.setAttributeValue(SunSipApp.PARAMETER_ENCODING,
                        SunSipApp.DEFAULT_CHARSET, attributes.getValue(i));
                }

                if (RuntimeTagNames.FORM_HINT_FIELD.equals(attributes.getQName(
                                i))) {
                    sunSipApp.setAttributeValue(SunSipApp.PARAMETER_ENCODING,
                        SunSipApp.FORM_HINT_FIELD, attributes.getValue(i));
                }
            }
        } else {
            super.startElement(element, attributes);
        }
    }

    /**
     * parsed an attribute of an element
     *
     * @param the element name
     * @param the attribute name
     * @param the attribute value
     * @return true if the attribute was processed
     */
    protected boolean setAttributeValue(XMLElement elementName,
        XMLElement attributeName, String value) {
        SunSipApp sunSipApp = (SunSipApp) getDescriptor();

        return false;
    }

    /**
     * receives notification of the value for a particular tag
     *
     * @param element the xml element
     * @param value it's associated value
     */
    public void setElementValue(XMLElement element, String value) {
        super.setElementValue(element, value);
    }

    /**
     * write the descriptor class to a DOM tree and return it
     *
     * @param parent node for the DOM tree
     * @param the descriptor to write
     * @return the DOM tree top node
     */
    public Node writeDescriptor(Node parent, Descriptor descriptor) {
        if (!(descriptor instanceof SipBundleDescriptor)) {
            throw new IllegalArgumentException(getClass() +
                " cannot handles descriptors of type " + descriptor.getClass());
        }

        SipBundleDescriptor bundleDescriptor = (SipBundleDescriptor) descriptor;
        Element web = (Element) super.writeDescriptor(parent, descriptor);

        SunSipApp sunSipApp = bundleDescriptor.getSunSipDescriptor();

        // security-role-mapping
        SecurityRoleMapping[] roleMappings = sunSipApp.getSecurityRoleMapping();

        if ((roleMappings != null) && (roleMappings.length > 0)) {
            SecurityRoleMappingNode srmn = new SecurityRoleMappingNode();

            for (int i = 0; i < roleMappings.length; i++) {
                srmn.writeDescriptor(web,
                    RuntimeTagNames.SECURITY_ROLE_MAPPING, roleMappings[i]);
            }
        }

        if (sunSipApp.getSessionConfig() != null) {
            SessionConfigNode scn = new SessionConfigNode();
            scn.writeDescriptor(web, RuntimeTagNames.SESSION_CONFIG,
                sunSipApp.getSessionConfig());
        }

        // ejb-ref*
        EjbRef[] ejbRefs = sunSipApp.getEjbRef();

        if ((ejbRefs != null) && (ejbRefs.length > 0)) {
            EjbRefNode node = new EjbRefNode();

            for (int i = 0; i < ejbRefs.length; i++) {
                node.writeDescriptor(web, RuntimeTagNames.EJB_REF, ejbRefs[i]);
            }
        }

        // resource-ref*
        ResourceRef[] resourceRefs = sunSipApp.getResourceRef();

        if ((resourceRefs != null) && (resourceRefs.length > 0)) {
            ResourceRefNode node = new ResourceRefNode();

            for (int i = 0; i < resourceRefs.length; i++) {
                node.writeDescriptor(web, RuntimeTagNames.RESOURCE_REF,
                    resourceRefs[i]);
            }
        }

        // resource-env-ref*
        ResourceEnvRef[] resourceEnvRefs = sunSipApp.getResourceEnvRef();

        if ((resourceEnvRefs != null) && (resourceEnvRefs.length > 0)) {
            ResourceEnvRefNode node = new ResourceEnvRefNode();

            for (int i = 0; i < resourceEnvRefs.length; i++) {
                node.writeDescriptor(web, RuntimeTagNames.RESOURCE_ENV_REF,
                    resourceEnvRefs[i]);
            }
        }

        // service-ref*
        if (bundleDescriptor.hasServiceReferenceDescriptors()) {
            ServiceRefNode serviceNode = new ServiceRefNode();

            for (Iterator serviceItr = bundleDescriptor.getServiceReferenceDescriptors()
                                                       .iterator();
                    serviceItr.hasNext();) {
                ServiceReferenceDescriptor next = (ServiceReferenceDescriptor) serviceItr.next();
                serviceNode.writeDescriptor(web,
                    WebServicesTagNames.SERVICE_REF, next);
            }
        }

        // message-destination-ref*
        MessageDestinationRefNode.writeMessageDestinationReferences(web,
            bundleDescriptor);

        // class-loader?
        ClassLoader classLoader = sunSipApp.getClassLoader();

        if (classLoader != null) {
            ClassLoaderNode cln = new ClassLoaderNode();
            cln.writeDescriptor(web, RuntimeTagNames.CLASS_LOADER, classLoader);
        }

        // locale-charset-info?
        if (sunSipApp.getLocaleCharsetInfo() != null) {
            LocaleCharsetInfoNode localeNode = new LocaleCharsetInfoNode();
            localeNode.writeDescriptor(web,
                RuntimeTagNames.LOCALE_CHARSET_INFO,
                sunSipApp.getLocaleCharsetInfo());
        }

        // parameter-encoding?
        if (sunSipApp.isParameterEncoding()) {
            Element parameter = (Element) appendChild(web,
                    RuntimeTagNames.PARAMETER_ENCODING);

            if (sunSipApp.getAttributeValue(SunSipApp.PARAMETER_ENCODING,
                        SunSipApp.FORM_HINT_FIELD) != null) {
                setAttribute(parameter, RuntimeTagNames.FORM_HINT_FIELD,
                    (String) sunSipApp.getAttributeValue(
                        SunSipApp.PARAMETER_ENCODING, SunSipApp.FORM_HINT_FIELD));
            }

            if (sunSipApp.getAttributeValue(SunSipApp.PARAMETER_ENCODING,
                        SunSipApp.DEFAULT_CHARSET) != null) {
                setAttribute(parameter, RuntimeTagNames.DEFAULT_CHARSET,
                    (String) sunSipApp.getAttributeValue(
                        SunSipApp.PARAMETER_ENCODING, SunSipApp.DEFAULT_CHARSET));
            }
        }

        // property*
        if (sunSipApp.getWebProperty() != null) {
            WebPropertyNode props = new WebPropertyNode();
            props.writeDescriptor(web, RuntimeTagNames.PROPERTY,
                sunSipApp.getWebProperty());
        }

        // message-destination*
        RuntimeDescriptorNode.writeMessageDestinationInfo(web, bundleDescriptor);

        // webservice-description*
        WebServiceRuntimeNode webServiceNode = new WebServiceRuntimeNode();
        webServiceNode.writeWebServiceRuntimeInfo(web, bundleDescriptor);

        // error-url
        if (sunSipApp.getAttributeValue(sunSipApp.ERROR_URL) != null) {
            setAttribute(web, RuntimeTagNames.ERROR_URL,
                sunSipApp.getAttributeValue(sunSipApp.ERROR_URL));
        }

        return web;
    }
}
