/***
 * Excerpted from "Domain-Driven Design Using Naked Objects",
 * published by The Pragmatic Bookshelf.
 * Copyrights apply to this code. It may not be used to create training material, 
 * courses, books, articles, and the like. Contact us if you are in doubt.
 * We make no guarantees that this code is fit for any purpose. 
 * Visit http://www.pragmaticprogrammer.com/titles/dhnako for more book information.
***/
package com.pragprog.dhnako.carserv.camel.inout.processors;

import java.util.List;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.nakedobjects.metamodel.adapter.NakedObject;

import com.pragprog.dhnako.carserv.camel.inout.messages.CustomerMessage;
import com.pragprog.dhnako.carserv.dom.customer.Customer;
import com.pragprog.dhnako.carserv.dom.customer.CustomerRepository;

public class LookUpEmailProcessor extends AbstractNakedObjectsProcessor {
	
	public void doProcess(Exchange exchange) {
		Message message = exchange.getIn();
		CustomerMessage customerMessage = (CustomerMessage) message.getBody();
		
		NakedObject customerRepositoryAdapter = getService("customers");
		
		CustomerRepository customerRepository = 
			(CustomerRepository) customerRepositoryAdapter.getObject();
		List<Customer> customers = customerRepository.findByName(
				customerMessage.getLastName(), customerMessage.getFirstName());

		Customer customer = first(customers);
		if (customer != null) {
			customerMessage.setEmail(customer.getEmailAddress());
		}
		message.setBody(customerMessage);
		exchange.setOut(message);
	}

	private <T> T first(List<T> list) {
		return list.size() > 0? list.get(0): null;
	}

}

