package com.tandbergtv.watchpoint.pmm.core;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import com.tandbergtv.cms.portal.util.transaction.Transactional;
import com.tandbergtv.watchpoint.pmm.dao.hibernate.HibernateContext;
import com.tandbergtv.watchpoint.pmm.entities.ProgressItem;
import com.tandbergtv.watchpoint.pmm.entities.Title;
import com.tandbergtv.watchpoint.pmm.title.ITitlePersistenceService;
import com.tandbergtv.workflow.core.event.DefaultMediator;
import com.tandbergtv.workflow.core.service.ServiceRegistry;

/**
 * Manages Progress Item entities.
 * 
 * @author Raj Prakash
 */
public class ProgressManager {
	private static final Logger logger = Logger
			.getLogger(ProgressManager.class);

	private ITitlePersistenceService titlePersistenceService;

	ProgressManager() {
		titlePersistenceService = ServiceRegistry.getDefault().lookup(
				ITitlePersistenceService.class);
	}

	/**
	 * Creates a new instance of this class.
	 */
	public static ProgressManager newInstance() {
		return new ProgressManager();
	}

	/**
	 * Creates or updates the progress item. If scheduleId is given, creates or
	 * updates progress item at title/schedule level. If scheduleId is not
	 * given, creates or updates progress item at title level.
	 */
	@Transactional
	public void updateStatus(long titleId, Long scheduleId, String status,
			String value, boolean success, String sourceComponentName,
			String sourceEntityName, String sourceId) {

		Title title = titlePersistenceService.get(titleId);
		if (title == null) {
			throw new RuntimeException("Cannot set progress for titleId: "
					+ titleId + " as title does not exist.");
		}
		String titleVersion = title.getAsset().getVersion();
		ProgressItem newPI = new ProgressItem(status, value, titleId,
				titleVersion, sourceComponentName, sourceEntityName, sourceId);
		newPI.setIsSuccess(success);
		newPI.setAssetListId(scheduleId);
		save(newPI);
	}

	/**
	 * Saves or Updates the given progress item.
	 */
	private void save(ProgressItem pi) {
		Long titleId = pi.getTitleId();
		Long scheduleId = pi.getAssetListId();

		Session session = HibernateContext.getContext().getCurrentSession();
		session.saveOrUpdate(pi);
		logger.debug("Updated progress item " + pi);
		DefaultMediator.getInstance().sendAsync(
				new ProgressEvent(this, scheduleId, Long.valueOf(titleId), pi
						.getName()));
	}
}
