/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2011-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.ws.jaxws.base.audit;

import java.util.concurrent.atomic.AtomicLong;

import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.ow2.util.auditreport.api.IAuditID;
import org.ow2.util.auditreport.api.ICurrentInvocationID;
import org.ow2.util.auditreport.impl.JaxwsAuditReport;
import org.ow2.util.auditreport.impl.event.Event;
import org.ow2.util.event.api.IEventService;
import org.ow2.util.event.impl.EventDispatcher;
import org.ow2.util.log.Log;
import org.ow2.util.log.LogFactory;

/**
 * A {@code JaxwsAuditHandler} is ...
 *
 * @author Guillaume Sauthier
 */
public class JaxwsEndpointAuditHandler extends AbstractJaxwsAuditHandler {

    public static final String REPORT_KEY = JaxwsEndpointAuditHandler.class.getName() + ".REPORT";

    public static final String AUDIT_ID_KEY = JaxwsEndpointAuditHandler.class.getName() + ".AUDIT_ID";

    public static final Log logger = LogFactory.getLog(JaxwsEndpointAuditHandler.class);

    private AtomicLong sequence = new AtomicLong();

    private boolean detailed = false;

    private ICurrentInvocationID current;
    
    /**
     * eventService to send events
     */
    private IEventService eventService = null;

    public JaxwsEndpointAuditHandler(ICurrentInvocationID current) {
       this(current,null);
    }

    public JaxwsEndpointAuditHandler(ICurrentInvocationID current,IEventService eventService) {
    	this.current = current;
    	this.eventService=eventService;
	}

	public boolean handleMessage(SOAPMessageContext context) {

        if (isOutbound(context)) {
            // Response
            // Close the report generation
            JaxwsAuditReport report = (JaxwsAuditReport) context.get(REPORT_KEY);
            if (report != null) {

                report.setEndProcessingTimestamp(System.nanoTime());

                Event event = new Event(report);
                
                if(eventService != null){
                    EventDispatcher d = (EventDispatcher) eventService.getDispatcher("JAXWS");
                    if(d == null) {
                        d = new EventDispatcher();
                        d.setNbWorkers(2);
                        d.start();
                        eventService.registerDispatcher("JAXWS", d);
                    }
                    eventService.getDispatcher("JAXWS").dispatch(event);
                }
                // Restore the Audit ID in the thread.
                // is equivalent to a current.pop() if it was existing
                IAuditID old = (IAuditID) context.get(AUDIT_ID_KEY);
                if (old != null) {
                    current.setAuditID(old);
                }
            }

        } else { // inbound
            // Request
            // Init the report generation

            IAuditID oldId = current.getAuditID();

            if (oldId != null) {

                // Generate a new ID (will appear as a new node in the UI)
                current.newInvocation();
                IAuditID id = current.getAuditID();

                // If there is no ID set, just abort report generation

                JaxwsAuditReport report = new JaxwsAuditReport();
                report.setKeyID(id.getID());
                report.setRequestTimeStamp(System.currentTimeMillis());
                report.setStartProcessingTimestamp(System.nanoTime());

                report.setServiceQName(context.get(MessageContext.WSDL_SERVICE).toString());
                report.setPortQName(context.get(MessageContext.WSDL_PORT).toString());
                report.setOperationQName(context.get(MessageContext.WSDL_OPERATION).toString());

                report.setSoapRoles(context.getRoles());

                // Store the report
                context.put(REPORT_KEY, report);

                // Store the old ID
                context.put(AUDIT_ID_KEY, oldId);
            }
        }
        return true;
    }

    public boolean isDetailed() {
        return detailed;
    }

    public void setDetailed(boolean detailed) {
        this.detailed = detailed;
    }
}
