/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2012 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.ipojo.interceptor.internal.handler;

import java.lang.reflect.Member;
import java.util.Date;
import java.util.Dictionary;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.felix.ipojo.ComponentInstance;
import org.apache.felix.ipojo.ConfigurationException;
import org.apache.felix.ipojo.InstanceManager;
import org.apache.felix.ipojo.PrimitiveHandler;
import org.apache.felix.ipojo.architecture.InstanceDescription;
import org.apache.felix.ipojo.metadata.Element;
import org.apache.felix.ipojo.parser.MethodMetadata;
import org.ow2.jonas.ipojo.interceptor.ComponentInstanceState;
import org.ow2.jonas.ipojo.interceptor.IInstanceProvider;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * iPOJO Interceptor handler
 *
 * @author Jeremy Cazaux
 */
public class iPOJOInterceptor extends PrimitiveHandler implements IInstanceProvider {

    /**
     * The logger
     */
    private static Log logger = LogFactory.getLog(iPOJOInterceptor.class);

    /**
     * Callback element
     */
    private static final String CALLBACK_ELEMENT = "callback";

    /**
     * Method attribute of a callback element
     */
    private static final String METHOD_ATTRIBUTE = "method";

    /**
     * The path to the deployable associate to the service
     */
    private String deployable;

    /**
     * The start time of the service
     */
    private Date startTime;

    /**
     * The shutdown time of the service
     */
    private Date shutdownTime;

    /**
     * Map between a {@link Throwable} and its timestamp
     */
    private Map<Throwable, Long> throwables = new LinkedHashMap<Throwable, Long>();

    /**
     * The prefix source of an ipojo instance
     */
    public static final String PREFIX_SOURCE = "ipojo/instance/";

    /**
     * {@inheritDoc}
     */
    @Override
    public void configure(final Element element, final Dictionary dictionary) throws ConfigurationException {
        InstanceManager instanceManager = getInstanceManager();

        // Traverse component's description looking for callback methods
        // For each callback method, register an interceptor
        Element[] callbacks = element.getElements(CALLBACK_ELEMENT);
        if (callbacks != null) {
            for (Element callback : callbacks) {

                // Find the method
                String name = callback.getAttribute(METHOD_ATTRIBUTE);
                MethodMetadata method = getPojoMetadata().getMethod(name);

                if (method == null) {
                    //TODO iPOJO bug (see FELIX-3835) - Inherit methods could not be retrieved
                    logger.warn("Could not register an interceptor for the method " + name + " of component " + getInstanceManager().getInstanceName() + " (method not found by PojoMetadata)");
                } else {
                    // Register an interceptor for the given method
                    instanceManager.register(method, this);
                }
            }
        }

    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onError(Object pojo, Member method, Throwable throwable) {
        throwables.put(throwable, System.currentTimeMillis());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void stateChanged(int state) {
        switch (adapt(state)) {
            case DISPOSED:
            case INVALID:
            case STOPPED:
                // Instance has been invalidated
                shutdownTime = new Date();
                break;
            case VALID:
                // instance is now valid
                startTime = new Date();
                shutdownTime = null;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void stop() {
        logger.debug("iPOJO interceptor of " + getInstanceManager().getInstanceName() + " has been stopped.");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void start() {
        logger.debug("iPOJO interceptor start on pojo " + getInstanceManager().getInstanceName());
    }

    public String getName() {
        return getInstanceManager().getInstanceName();
    }

    public ComponentInstanceState getStateComponent() {
        return adapt(getInstanceManager().getState());
    }

    private static ComponentInstanceState adapt(int state) {
        switch (state) {
            case ComponentInstance.DISPOSED:
                return ComponentInstanceState.DISPOSED;
            case ComponentInstance.INVALID:
                return ComponentInstanceState.INVALID;
            case ComponentInstance.VALID:
                return ComponentInstanceState.VALID;
            case ComponentInstance.STOPPED:
                return ComponentInstanceState.STOPPED;
            default:
                throw new IllegalArgumentException("Invalid ComponentInstance state: " + state);
        }
    }

    public String getDeployable() {
        return null;
    }

    public Date getStartTime() {
        return startTime;
    }

    public Long getUpTime() {
        if (this.startTime != null) {
            Date lastTime;
            if (this.shutdownTime == null) {
                // now
                lastTime = new Date();
            } else {
                lastTime = this.shutdownTime;
            }
            return lastTime.getTime() - this.startTime.getTime();
        } else {
            return null;
        }
    }

    public Date getShutdownTime() {
        return shutdownTime;
    }

    public Map<Throwable, Long> getThrowables() {
        return throwables;
    }

    public String getSource() {
        return PREFIX_SOURCE + getName();
    }

    /**
     * {@inheritDoc}
     */
    public InstanceDescription getInstanceDescription() {
        return getInstanceManager().getInstanceDescription();
    }
}
