package it.mice.voila.runtime.mail.listeners;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;

import it.mice.voila.runtime.events.OperationSuccessEvent;
import it.mice.voila.runtime.mail.beans.MailEvent;
import it.mice.voila.runtime.mail.manager.MailManager;

public class MailEventConsumerListener implements ApplicationListener<OperationSuccessEvent> {
	/**
	 * default logger.
	 */
	private static final Log LOGGER = LogFactory.getLog(MailEventConsumerListener.class);

	@Autowired
	private MailManager mailManager;
	
	public void onApplicationEvent(OperationSuccessEvent event) {
		String operationName = (String)event.getSource();
		String eventId = null;
		if (operationName.startsWith("/manage/")) {
			eventId = operationName.substring(8).replaceAll("\\/", "_").replaceAll("\\*", "");
			if (eventId.endsWith("_")) {
				eventId = eventId.substring(0, eventId.length() - 1);
			}
		} else {
			eventId = operationName;
		}
		if (LOGGER.isDebugEnabled()) {
			LOGGER.debug("Received operation success event name " + operationName + ", resolved to mail event id " + eventId);
		}
		if (eventId != null) {
			MailEvent mailEvent = mailManager.getMailEvents().get(eventId);
			if (mailEvent != null) {
				if (LOGGER.isDebugEnabled()) {
					LOGGER.debug("Found mail event " + eventId + " for operation " + operationName + ", executing...");
				}
				Map<String, Object> ctx = new HashMap<String, Object>();
				ctx.put("form", event.getForm());
				mailManager.sendEmailByEvent(mailEvent, ctx, null);
			}
		}
	}
}
