/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2006, Red Hat Middleware LLC, and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This 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 software 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 software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.soa.bpel.samples.quickstart.purchase;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jws.WebService;
import javax.servlet.ServletContext;
import javax.xml.ws.WebServiceContext;
import javax.xml.ws.handler.MessageContext;

/**
 * Invoice endpoint bean.
 * 
 * @author Jeff DeLong
 * @author Alejandro Guizar
 */
@WebService(endpointInterface = "org.jboss.soa.bpel.samples.quickstart.purchase.ComputePricePT", targetNamespace = "http://manufacturing.org/wsdl/purchase", serviceName = "invoiceSVC", portName = "computePriceSP")
public class ComputePricePT_Impl implements ComputePricePT {

	@Resource
	private Queue invoiceQueue;
	@Resource
	private ConnectionFactory connectionFactory;

	@Resource
	private WebServiceContext serviceContext;

	private final Logger logger =
			Logger.getLogger(ComputePricePT_Impl.class.getName());

	private static final String ORDER_ID_ATTR = "invoice.orderId";
	private static final String LINE_PRICE_ATTR = "invoice.linePrice";

	public void initiatePriceCalculation(CustomerInfo customerInfo,
			PurchaseOrder purchaseOrder) {
		MessageContext messageContext = serviceContext.getMessageContext();
		ServletContext servletContext =
				(ServletContext) messageContext.get(MessageContext.SERVLET_CONTEXT);
		servletContext.setAttribute(ORDER_ID_ATTR, purchaseOrder.getOrderId());
		// In our system the part number is also the unit price!
		servletContext.setAttribute(LINE_PRICE_ATTR,
				(float) purchaseOrder.getQuantity() * purchaseOrder.getPartNumber());
	}

	public void sendShippingPrice(ShippingInfo shippingInfo) {
		try {
			sendInvoiceMessage(shippingInfo.getShippingPrice());
		}
		catch (JMSException e) {
			logger.log(Level.SEVERE, "failed to send invoice message", e);
		}
	}

	protected void sendInvoiceMessage(float shippingPrice) throws JMSException {
		MessageContext messageContext = serviceContext.getMessageContext();
		ServletContext servletContext =
				(ServletContext) messageContext.get(MessageContext.SERVLET_CONTEXT);
		Integer orderId = (Integer) servletContext.getAttribute(ORDER_ID_ATTR);
		Float linePrice = (Float) servletContext.getAttribute(LINE_PRICE_ATTR);
		float amount = linePrice + shippingPrice;

		// create a connection
		Connection connection = connectionFactory.createConnection();
		try {
			// create a session
			Session session =
					connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
			try {
				// create the message
				MapMessage invoiceMessage = session.createMapMessage();
				invoiceMessage.setInt("orderId", orderId);
				invoiceMessage.setFloat("amount", amount);

				// send it!
				MessageProducer producer = session.createProducer(invoiceQueue);
				producer.send(invoiceMessage);

				logger.log(
						Level.FINE,
						"sent invoice message for PO #{0,number,integer} with amount {1,number,currency}",
						new Object[] { orderId, amount });
			}
			finally {
				session.close();
			}
		}
		finally {
			connection.close();
		}
	}
}
