/**
 * 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.report.extensions.bundles.internal;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;
import org.ow2.jonas.report.api.IReportExtension;
import org.ow2.jonas.report.extensions.bundles.generated.BundleType;
import org.ow2.jonas.report.extensions.bundles.generated.Bundles;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Represents a bundles report extension
 * @author Jeremy Cazaux
 */
public class BundlesReportExtension implements IReportExtension, FrameworkListener, BundleListener {

    /**
     * The logger
     */
    public static final Log logger = LogFactory.getLog(BundlesReportExtension.class);
    
    /**
     * EOL     *
     */
    public static final String EOL = "\n";

    /**
     * Path to the XSD
     */
    public static final String XSD_PATH = "xsd/bundles-report.xsd";

    /**
     * List of {@link BundleType}
     */
    private List<BundleType> bundles;

    /**
     * The {@link BundleContext}
     */
    private BundleContext bundleContext;

    /**
     * Default constructor
     */
    public BundlesReportExtension(final BundleContext bundleContext) {
        this.bundles = new ArrayList<BundleType>();
        this.bundleContext = bundleContext;
    }

    /**
     * Validate callback
     */
    public void start() {
        this.bundleContext.addBundleListener(this);
        this.bundleContext.addFrameworkListener(this);
    }

    /**
     * Invalidate callback
     */
    public void stop() {
        this.bundleContext.removeBundleListener(this);
        this.bundleContext.removeFrameworkListener(this);
    }

    /**
     * {@inheritDoc}
     */
    public Object generateReport() {
        Bundles bundles = new Bundles();
        List<BundleType> bundleTypeList = bundles.getBundle();
        bundleTypeList.addAll(this.bundles);
        return bundles;
    }

    /**
     * {@inheritDoc}
     */
    public Source getXsd() {
        InputStream xsd = getRootClass().getClassLoader().getResourceAsStream(XSD_PATH);
        Source source = null;
        if (xsd != null) {
            source = new StreamSource(xsd);
        } else {
            logger.error("Cannot find XSD " + XSD_PATH);
        }
        return source;
    }

    /**
     * {@inheritDoc}
     */
    public Class getRootClass() {
        return Bundles.class;
    }

    /**
     * {@inheritDoc}
     */
    public void frameworkEvent(final FrameworkEvent frameworkEvent) {
        //get the stack trace of the throwable
        Throwable throwable = frameworkEvent.getThrowable();
        if (throwable != null) {
            StringBuilder stackTrace = new StringBuilder();
            getStackTrace(stackTrace, throwable, true);
            BundleType bundleType  = getBundle(frameworkEvent.getBundle().getBundleId());
            if (bundleType != null) {
                bundleType.getError().add(stackTrace.toString());
            }
        }
    }

    /**
     * {@inheritDoc}
     */
    public void bundleChanged(final BundleEvent bundleEvent) {
        if (bundleEvent != null) {
            Bundle bundle = bundleEvent.getBundle();
            if (bundle != null) {
                long bundleId = bundle.getBundleId();
                BundleType bundleType = getBundle(bundleId);
                if (bundleType == null) {
                    bundleType = new BundleType();
                    bundleType.setId(bundleId);
                    bundleType.setSymbolicName(bundle.getSymbolicName());
                    bundleType.setVersion(bundle.getVersion().toString());
                    bundleType.setLocation(bundle.getLocation());
                    this.bundles.add(bundleType);
                }
                
                int state = bundle.getState();
                switch (state) {
                    case Bundle.UNINSTALLED:
                        bundleType.setState("Uninstalled");
                        break;
                    case Bundle.INSTALLED:
                        bundleType.setState("Installed");
                        break;
                    case Bundle.RESOLVED:
                        bundleType.setState("Resolved");
                        break;
                    case Bundle.STARTING:
                        bundleType.setState("Starting");
                        break;
                    case Bundle.STOPPING:
                        bundleType.setState("Stopping");
                        break;
                    case Bundle.ACTIVE:
                        bundleType.setState("Active");
                        break;
                }
            }      
        }     
    }

    /**
     * @param id The id of a bundle to retrieve
     * @return the {@link BundleType}
     */
    private BundleType getBundle(long id) {
        for (BundleType bundle: this.bundles) {
            if (bundle.getId() == id) {
                return bundle;
            }
        }
        return null;
    }

    /**
     *
     * @param stringBuilder The {@link StringBuilder} to store the stacktrace
     * @param throwable The {@link Throwable}
     * @param isRootThrowable True if this is the root throwable
     */
    private void getStackTrace(final StringBuilder stringBuilder, final Throwable throwable,
                               final boolean isRootThrowable) {
        if (throwable != null) {
            if (isRootThrowable) {
                stringBuilder.append(throwable.getClass().getName());
            } else {
                stringBuilder.append("Caused by : " + throwable.getClass().getName());
            }
            String message = throwable.getMessage();
            if (message != null) {
                stringBuilder.append(" : " + throwable.getMessage());
            }
            stringBuilder.append(EOL);
            for (StackTraceElement stackTraceElement: throwable.getStackTrace()) {
                stringBuilder.append("         at " + stackTraceElement + EOL);
            }
            Throwable cause = throwable.getCause();
            if (cause != null) {
                getStackTrace(stringBuilder, throwable.getCause(), false);
            }
        }
    }
}
