/*
 * 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.
 */
package com.ericsson.ssa.config;

import com.ericsson.ssa.sip.Layer;

import com.sun.org.apache.commons.digester.Rule;

import org.apache.tomcat.util.IntrospectionUtils;

import org.xml.sax.Attributes;

import java.lang.reflect.Method;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;


public class LayerRule extends Rule {
    private static final Logger m_Log = (Logger) Logger.getLogger(
            "SipContainer");
    private String m_classNameAttribute = "className";
    Layer layer = null;

    public void begin(String ns, String n, Attributes attributes)
        throws Exception {
        // The className attribute has to be defined in xml,
        // otherwise we cannot retreive the Layer instance
        String className = attributes.getValue(m_classNameAttribute);

        if (className == null) {
            throw new Exception("Attribute " + m_classNameAttribute +
                " is missing");
        }

        // Find the singelton instance for the className class.
        try {
            Class<?> layerClass = Class.forName(className);
            Map<String, String> attribs = new HashMap<String, String>();

            for (int i = 0; i < attributes.getLength(); i++) {
                String name = attributes.getLocalName(i);

                if ("".equals(name)) {
                    name = attributes.getQName(i);
                }

                String parameter = attributes.getValue(i);

                // We continue for attribute "className" and "objectName".
                // They are for creation and identification but not a attribute
                // of the class
                if (name.equals("objectName")) {
                    registerComponent(null, parameter);

                    continue;
                }

                if (name.equals(m_classNameAttribute)) {
                    continue;
                }

                if (name.equals("registerInFactory")) {
                    Class<?> singletonClass = Class.forName(parameter);
                    Class<?>[] input = { Class.class };
                    Object[] inObj = { layerClass };
                    Method m = singletonClass.getMethod("initInstance", input);

                    if (m_Log.isLoggable(Level.FINE)) {
                        m_Log.log(Level.FINE,
                            "about to invoke method 'initInstance' of class " +
                            singletonClass);
                    }

                    m.invoke(singletonClass, inObj);
                }

                attribs.put(name, parameter);

                // Set the property
                // IntrospectionUtils.setProperty( instance, name, parameter);
            }

            Method method = layerClass.getMethod("getInstance", (Class[]) null);
            Object object = method.invoke((Object) null, (Object[]) null);

            // The getInstance() method may return null if the layer is configured
            // to exclude itself via domain.xml
            if (object != null) {
                if (object instanceof Layer) {
                    layer = (Layer) object;
                    // Register the Layer With LayerHandler
                    LayerHandler.getInstance().addLayer(layer);

                    Iterator<String> i = attribs.keySet().iterator();

                    while (i.hasNext()) {
                        String name = i.next();
                        String parameter = attribs.get(name);
                        setAttribute(name, parameter);
                    }
                }
            }
        } catch (Exception e) {
            m_Log.log(Level.SEVERE,
                "tried to invoke " + className +
                ".getInstance(), caught exception: " + e +
                ", underlying cause: " + e.getCause().getMessage());
            throw new Exception("Exception invoking getInstance for class " +
                className);
        }
    }

    public void registerComponent(Object bean, String objectName) {
        // TODO PEPE Register Component with JMX
    }

    public void setAttribute(String attribute, String value) {
        IntrospectionUtils.setProperty(layer, attribute, value);
    }
}
