/**
 * 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.deployables.internal;

import org.osgi.service.event.Event;
import org.ow2.jonas.management.DeployableState;
import org.ow2.jonas.management.J2EEServerService;
import org.ow2.jonas.report.api.IReportExtension;
import org.ow2.jonas.report.extensions.deployable.generated.DeployableType;
import org.ow2.jonas.report.extensions.deployable.generated.Deployables;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Represents a Deployable report extension
 * @author Jeremy Cazaux
 */
public class DeployablesReportExtension implements IReportExtension {

    /**
     * The logger
     */
    public static final Log logger = LogFactory.getLog(DeployablesReportExtension.class);

    /**
     * Deployable topic
     */
    public static final String DEPLOYABLE_TOPIC = "deployablePublisherTopic";

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

    /**
     * List of {@link DeployableType}
     */
    private List<DeployableType> deployableTypeList;

    /**
     * Map between a deployable and a time (used to get the start time and end time of deployment and undeployment operation)
     */
    private Map<DeployableType, Long> deployableMap;

    /**
     * Default constructor
     */
    public DeployablesReportExtension() {
        this.deployableTypeList = new ArrayList<DeployableType>();
        this.deployableMap = new HashMap<DeployableType, Long>();
    }

    /**
     * {@inheritDoc}
     */
    public Object generateReport() {
        Deployables deployablesType = new Deployables();
        deployablesType.getDeployable().addAll(this.deployableTypeList);
        return deployablesType;
    }

    /**
     * {@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 Deployables.class;
    }

    /**
     * Handle deployables notification
     */
    public void handleDeployable(final Event event) {
        boolean postDeployedOperation = false;
        boolean postUndeployedOperation = false;

        if (DEPLOYABLE_TOPIC.equals(event.getTopic())) {
            String name = String.class.cast(event.getProperty(J2EEServerService.EVENT_DEPLOYABLE_NAME_KEY));
            DeployableType deployableType = getDeployable(name);
            if (deployableType == null) {
                //create a new deployable item
                deployableType = new DeployableType();

                Object object = event.getProperty(J2EEServerService.EVENT_DEPLOYABLE_NAME_KEY);
                if (object != null) {
                    deployableType.setName(String.class.cast(object));
                }
                object = event.getProperty(J2EEServerService.EVENT_DEPLOYABLE_PATH_KEY);
                if (object != null) {
                    deployableType.setPath(String.class.cast(object));
                }
                object = event.getProperty(J2EEServerService.EVENT_DEPLOYABLE_STATE_KEY);
                if (object != null) {
                    DeployableState deployableState = DeployableState.class.cast(object);
                    deployableType.setState(deployableState.toString());
                }
                object = event.getProperty(J2EEServerService.EVENT_DEPLOYABLE_SOURCE_KEY);
                if (object != null) {
                    deployableType.setSource(String.valueOf(object));
                }

                this.deployableTypeList.add(deployableType);
            } else {
                //update the state of the deployable
                Object object = event.getProperty(J2EEServerService.EVENT_DEPLOYABLE_STATE_KEY);
                if (object != null) {
                    DeployableState deployableState = DeployableState.class.cast(object);
                    String curentState = deployableState.toString();
                    String state = deployableType.getState();

                    if (!curentState.equals(state)) {

                        //notification has been sent from a post deploy callback
                        if (DeployableState.DEPLOYED.toString().equals(curentState)) {
                            postDeployedOperation = true;
                        } else {
                            //notification has been sent from a post undeploy callback
                            postUndeployedOperation = true;
                        }
                    }

                    deployableType.setState(deployableState.toString());
                }
            }

            Object object = event.getProperty(J2EEServerService.EVENT_DEPLOYABLE_CURRENT_TIME);
            if (object != null) {
                Long currentTime = Long.class.cast(object);
                Long time = this.deployableMap.get(deployableType);
                if (time != null) {
                    if (postDeployedOperation) {
                        Long startTime = currentTime - time;
                        deployableType.setStartTime(startTime);
                        postDeployedOperation = false;
                    } else if (postUndeployedOperation) {
                        Long shutdownTime = currentTime - time;
                        deployableType.setShutdownTime(shutdownTime);
                        postUndeployedOperation = false;
                    }
                }
                this.deployableMap.put(deployableType, currentTime);
            }
        }
    }

    /**
     * @param name The name of a deployable to retrieve
     * @return the associated {@link DeployableType} if found. Otherwise, return null.
     */
    private DeployableType getDeployable(final String name) {
        for (DeployableType deployableType: this.deployableTypeList) {
            String deployableName = deployableType.getName();
            if (deployableName != null && deployableName.equals(name)) {
                return deployableType;
            }
        }
        return null;
    }
}
