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

import org.ow2.jonas.endpoint.collector.util.Util;
import org.ow2.jonas.jmx.JmxService;
import org.ow2.jonas.management.J2EEServerService;
import org.ow2.jonas.report.api.IReportExtension;
import org.ow2.jonas.report.extensions.server.info.generated.DateTimeType;
import org.ow2.jonas.report.extensions.server.info.generated.ServerInfo;
import org.ow2.jonas.service.report.util.Utility;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.Date;

/**
 * Represents a Server info report extension
 * @author Jeremy Cazaux
 */
public class ServerInfoReportExtension implements IReportExtension {

    /**
     * JOnAS Root path
     */
    private static final String JONAS_ROOT = System.getProperty("jonas.root");

    /**
     * JOnAS Base path
     */
    private static final String JONAS_BASE = System.getProperty("jonas.base");

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

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

    /**
     * The {@link J2EEServerService}
     */
    private J2EEServerService j2EEServerService;

    /**
     * The {@link org.ow2.jonas.jmx.JmxService}
     */
    private JmxService jmxService;

    /**
     * {@inheritDoc}
     */
    public Object generateReport() {
        ServerInfo serverInfo = new ServerInfo();
        if (this.j2EEServerService != null) {
            ObjectName objectName = Util.getObjectName(this.jmxService.getDomainName() +
                    ":j2eeType=J2EEServer,name=" + this.jmxService.getJonasServerName());
            MBeanServer mBeanServer = this.jmxService.getJmxServer();
            String state = String.valueOf(Util.getMBeanAttributeValue(objectName, "state", mBeanServer));
            String version = String.valueOf(Util.getMBeanAttributeValue(objectName, "serverVersion", mBeanServer));

            Date startTime =  new Date(Long.valueOf(String.valueOf(Util.getMBeanAttributeValue(objectName,
                    "startTime", mBeanServer))));
            String upTime = String.valueOf(Util.getMBeanAttributeValue(objectName, "uptime", mBeanServer));

            //TODO endTime of the server?

            if (startTime != null) {
                DateTimeType dateTime = new DateTimeType();
                dateTime.setDateTime(Utility.date2XMLGregorianCalendar(startTime));
                dateTime.setTimestamp(BigInteger.valueOf(startTime.getTime()));
                serverInfo.setStartTime(dateTime);
            }

            if (upTime != null) {
                Long upTimLong = Long.valueOf(upTime);
                DateTimeType dateTime = new DateTimeType();
                dateTime.setDateTime(Utility.date2XMLGregorianCalendar(new Date(upTimLong)));
                dateTime.setTimestamp(BigInteger.valueOf(upTimLong));
                serverInfo.setUpTime(dateTime);
            }

            serverInfo.setState(state);
            serverInfo.setJonasRoot(JONAS_ROOT);
            serverInfo.setJonasBase(JONAS_BASE);
            serverInfo.setVersion(version);
        }
        return serverInfo;
    }

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

    /**
     * @param j2EEServerService The {@link org.ow2.jonas.management.J2EEServerService} to bind
     */
    public void bindJ2EEService(final J2EEServerService j2EEServerService) {
        this.j2EEServerService = j2EEServerService;
    }

    /**
     * @param j2EEServerService The {@link J2EEServerService} to unbind
     */
    public void unbindJ2EEService(final J2EEServerService j2EEServerService) {
        //this.j2EEServerService = null;
    }

    /**
     * @param jmxService The {@link JmxService} to bind
     */
    public void bindJmxService(final JmxService jmxService) {
        this.jmxService = jmxService;
    }

    /**
     * @param jmxService The {@link JmxService} to unbind
     */
    public void unbindJmxService(final JmxService jmxService) {
        //this.jmxService = null;
    }
}
