/**
 * DeleteTitleAction.java
 * Created Aug 12, 2008
 * Copyright (c) TANDBERG Television 2007-2008
 */
package com.tandbergtv.watchpoint.pmm.web.actions.title;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.MappingDispatchAction;

import com.tandbergtv.watchpoint.pmm.entities.IAssetList;
import com.tandbergtv.watchpoint.pmm.entities.Schedule;
import com.tandbergtv.watchpoint.pmm.entities.ScheduleStatus;
import com.tandbergtv.watchpoint.pmm.entities.Title;
import com.tandbergtv.watchpoint.pmm.entities.TitleListType;
import com.tandbergtv.watchpoint.pmm.title.ITitlePersistenceService;
import com.tandbergtv.watchpoint.pmm.web.formbeans.title.TitleForm;
import com.tandbergtv.workflow.core.service.ServiceRegistry;
import com.tandbergtv.workflow.web.common.StaticCodes;

/**
 * Deletes a title
 * 
 * @author Sahil Verma
 */
public class DeleteTitleAction extends MappingDispatchAction {

	private static final Logger logger = Logger.getLogger(DeleteTitleAction.class);
	
	public ActionForward delete(ActionMapping mapping, ActionForm actionform,
		HttpServletRequest request, HttpServletResponse response) throws Exception {
		TitleForm form = (TitleForm) actionform;
		ITitlePersistenceService service = ServiceRegistry.getDefault().lookup(ITitlePersistenceService.class);
		
		ActionMessages messages = new ActionMessages();
		
		long titleId = Long.valueOf(form.getId());
		if (canDeleteTitle(titleId)) {
			service.delete(titleId);
			form.setTitleDeleted(true);
		} else {
			logger.error(titleId + " is associated with planner(s) or pitch schedule(s). Hence cannot delete it.");
			messages.add(StaticCodes.INFO_ERROR, new ActionMessage("title.delete.errors",
					"Title is associated with planner(s) or pitch schedule(s)."));
			saveErrors(request, messages);
			form.setTitleDeleted(false);
		}
		request.setAttribute("Multiple Titles", false);
		return mapping.findForward("success");
	}
	
	/**
	 * If this title is associated with an active planner/pitch schedule (in the past or future), 
	 * then this title cannot be deleted.
	 * 
	 * @param title
	 * @return
	 */
	private boolean canDeleteTitle(long titleId) {
		ITitlePersistenceService service = ServiceRegistry.getDefault().lookup(ITitlePersistenceService.class);
		Title title = service.get(titleId);
		
		for (IAssetList list : title.getTitlelists()) {
			Schedule s = ((Schedule) list);
			if (s.getType() == TitleListType.PLANNER
					|| (s.getType() == TitleListType.PITCH && s.getStatus() == ScheduleStatus.APPROVED)) {
				return false;
			}
		}
		return true;
	}

}
