/**
 * PitchNotificationGenerator.java
 * Created Jul 2, 2008
 * Copyright (c) TANDBERG Television 2007-2008
 */
package com.tandbergtv.watchpoint.pmm.schedule.notify;

import java.text.SimpleDateFormat;
import java.util.Collection;

import com.tandbergtv.watchpoint.pmm.entities.Context;
import com.tandbergtv.watchpoint.pmm.entities.IContainer;
import com.tandbergtv.watchpoint.pmm.entities.Schedule;
import com.tandbergtv.watchpoint.pmm.entities.Title;
import com.tandbergtv.watchpoint.pmm.schedule.ScheduleRuntimeException;
import com.tandbergtv.watchpoint.pmm.util.ContextManager;
import com.tandbergtv.workflow.core.service.ServiceRegistry;
import com.tandbergtv.workflow.core.service.cache.ICacheService;

/**
 * Generates notifications for a pitch schedule
 * 
 * @author Sahil Verma
 */
public class PitchNotificationGenerator extends AbstractNotificationGenerator {

	/* (non-Javadoc)
	 * @see com.tandbergtv.watchpoint.pmm.schedule.notify.AbstractNotificationGenerator#getType()
	 */
	protected String getType() {
		return "pitch";
	}

	/* (non-Javadoc)
	 * @see com.tandbergtv.watchpoint.pmm.schedule.notify.AbstractNotificationGenerator#addMessage(com.tandbergtv.watchpoint.pmm.schedule.notify.Notification, java.lang.String)
	 */
	protected void addMessage(Notification notification, String status, Collection<Title> titles) {
		String message = super.constructMessage(status, titles);
		Schedule schedule = notification.getSchedule();
		String destination = getDestination(schedule);
		String date = new SimpleDateFormat("yyyy-MM-dd").format(schedule.getDate());
		
		notification.addMessage("Pitch on " + date + " to " + destination + ", " + message);
	}
	
	@SuppressWarnings("unchecked")
	private String getDestination(Schedule schedule) {
		long contextId = schedule.getContextID().longValue();
		ICacheService<IContainer> cache = 
			(ICacheService<IContainer>)ServiceRegistry.getDefault().lookup("Container Cache");
		
		if (cache != null) {
			IContainer container = cache.get(contextId);
			
			if (container != null)
				return container.getContainerName();
		}
		
		Context context = ContextManager.getInstance().getContext(contextId);
		
		if (context != null)
			return context.getContainer().getContainerName();
		
		throw new ScheduleRuntimeException("Cannot find destination " + contextId + " for schedule " + schedule);
	}

	/* (non-Javadoc)
	 * @see com.tandbergtv.watchpoint.pmm.schedule.notify.AbstractNotificationGenerator#isTitleDelayed(com.tandbergtv.watchpoint.pmm.entities.Title, java.lang.String)
	 */
	@Override
	protected boolean isTitleDelayed(Title title, Schedule schedule, String status) {
		// If the progress status is not achieved, the title is considered delayed.
		return (schedule.getProgressItem(title, status) == null);
	}
}
