/**
 * ScheduleAction.java
 * Created Jun 2, 2008
 * Copyright (c) TANDBERG Television 2007-2008
 */
package com.tandbergtv.watchpoint.pmm.web.schedule;

import java.text.SimpleDateFormat;
import java.util.Date;

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.ActionRedirect;
import org.apache.struts.actions.MappingDispatchAction;

import com.tandbergtv.watchpoint.pmm.entities.DistributionSchedule;
import com.tandbergtv.watchpoint.pmm.entities.Planner;
import com.tandbergtv.watchpoint.pmm.entities.Schedule;
import com.tandbergtv.watchpoint.pmm.entities.ScheduleStatus;
import com.tandbergtv.watchpoint.pmm.schedule.ISchedulePersistenceService;
import com.tandbergtv.workflow.core.service.ServiceRegistry;
import com.tandbergtv.workflow.web.util.CommonUtils;

/**
 * This action class is the controller for the schedule CRUD view
 * 
 * @author Sahil Verma
 */
public class ScheduleAction extends MappingDispatchAction {

	private static final Logger logger = Logger.getLogger(ScheduleAction.class);

	private ISchedulePersistenceService service;

	/**
	 * Creates a ScheduleAction
	 */
	public ScheduleAction() {
		super();
		this.service = ServiceRegistry.getDefault().lookup(ISchedulePersistenceService.class);
	}

	/**
	 * Displays a schedule
	 */
	public ActionForward get(ActionMapping mapping, ActionForm actionform,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		ScheduleForm form = (ScheduleForm) actionform;
		String id = form.getScheduleId();
		logger.debug("Schedule id " + id);

		Schedule schedule = service.get(Long.parseLong(id));

		ScheduleFormPopulator.populateScheduleForm(form);

		form.setSchedule(schedule);

		return mapping.findForward("default");
	}

	/**
	 * Displays the schedule create page
	 */
	public ActionForward showCreatePage(ActionMapping mapping, ActionForm actionform,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		ScheduleForm form = (ScheduleForm) actionform;

		ScheduleFormPopulator.populateScheduleForm(form);

		return mapping.findForward("default");
	}

	/**
	 * Saves a schedule
	 */
	public ActionForward save(ActionMapping mapping, ActionForm actionform,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		ScheduleForm form = (ScheduleForm) actionform;
		Schedule schedule = getSchedule(form);
		
		service.save(schedule);

		form.setScheduleId(schedule.getId().toString());

		ActionRedirect redirect = new ActionRedirect(mapping.findForward("default"));

		redirect.addParameter("scheduleId", schedule.getId().toString());
		redirect.addParameter("spec", form.getSpec());

		return redirect;
	}

	/**
	 * Changes the status of a pitch schedule
	 */
	public ActionForward changeStatus(ActionMapping mapping, ActionForm actionform,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		ScheduleForm form = (ScheduleForm) actionform;
		String id = form.getScheduleId();
		logger.debug("Schedule id " + id);

		Schedule schedule = service.get(Long.parseLong(id));

		if (schedule instanceof Planner)
			throw new RuntimeException("Cannot change status of planner " + schedule);

		ScheduleStatus status = schedule.getStatus();

		/*
		 * State xitions - NEW, READY -> APPROVED - APPROVED -> READY And why isn't this in the
		 * model??
		 */
		if (status == ScheduleStatus.NEW || status == ScheduleStatus.READY)
			schedule.setStatus(ScheduleStatus.APPROVED);
		else
			schedule.setStatus(ScheduleStatus.NEW);

		service.save(schedule);

		ActionRedirect redirect = new ActionRedirect(mapping.findForward("default"));

		redirect.addParameter("scheduleId", schedule.getId().toString());
		redirect.addParameter("spec", form.getSpec());

		return redirect;
	}

	/**
	 * Deletes a schedule
	 */
	public ActionForward delete(ActionMapping mapping, ActionForm actionform,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		ScheduleForm form = (ScheduleForm) actionform;
		String id = form.getScheduleId();
		logger.debug("Schedule id " + id);

		Schedule schedule = service.get(Long.parseLong(id));

		service.delete(schedule);

		ActionRedirect redirect = new ActionRedirect(mapping.findForward("default"));
		redirect.addParameter("spec", form.getSpec());

		return redirect;
	}

	/**
	 * Returns the schedule from the information in the form. If the form has the schedule id, it's
	 * just a simple lookup. Otherwise a new schedule is created.
	 * 
	 * @return
	 */
	private Schedule getSchedule(ScheduleForm form) throws Exception {
		Long sourcePartnerId = null;

		String tmp = form.getSourcePartnerId();

		if (tmp != null && tmp.length() > 0)
			sourcePartnerId = Long.parseLong(tmp);

		Long contextId = Long.parseLong(form.getContextId());
		String format = CommonUtils.getApplicationUIResourceBundle().getString(
				CommonUtils.DATE_FORMAT);
		Date date = new SimpleDateFormat(format).parse(form.getDate());

		/* Uhhh, no planners for now */
		DistributionSchedule schedule = null;

		if (form.getScheduleId() != null && form.getScheduleId().trim().length() > 0) {
			schedule = (DistributionSchedule) service.get(Long.parseLong(form.getScheduleId()));
			schedule.setPitchDate(date);
			schedule.setContextID(contextId);
			schedule.setSourcePartnerID(sourcePartnerId);
		} else {
			schedule = new DistributionSchedule(sourcePartnerId, contextId, date);
		}

		return schedule;
	}

}
