/**
 * SchedulePersistenceService.java
 * Created Apr 23, 2008
 * Copyright (c) TANDBERG Television 2007-2008
 */
package com.tandbergtv.watchpoint.pmm.schedule;

import java.io.Serializable;

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.AssetList;
import com.tandbergtv.watchpoint.pmm.entities.Schedule;

/**
 * Default implementation of the schedule persistence service which persists schedules to a datastore
 * 
 * @author Sahil Verma
 */
public class SchedulePersistenceService implements ISchedulePersistenceService {

	private static final Logger logger = Logger.getLogger(SchedulePersistenceService.class);

	/* (non-Javadoc)
	 * @see com.tandbergtv.watchpoint.pmm.schedule.ISchedulePersistenceService#delete(com.tandbergtv.watchpoint.pmm.entities.Schedule)
	 */	
	@Transactional
	public void delete(Schedule schedule) {
		try {
			Session session = getSession();

			schedule.setIsActive(false);
			schedule.removeTitles();

			session.saveOrUpdate(schedule);
			logger.debug("Deleted schedule " + schedule);
		} catch (Exception e) {
			throw new RuntimeException("Failed to delete " + schedule, e);
		}
	}

	/* (non-Javadoc)
	 * @see com.tandbergtv.watchpoint.pmm.schedule.ISchedulePersistenceService#get(java.io.Serializable)
	 */
	@Transactional
	public Schedule get(Serializable id) {
		Session session = getSession();
		Schedule schedule = (Schedule) session.load(AssetList.class, id);

		return schedule;
	}

	/* (non-Javadoc)
	 * @see com.tandbergtv.watchpoint.pmm.schedule.ISchedulePersistenceService#save(com.tandbergtv.watchpoint.pmm.entities.Schedule)
	 */
	@Transactional
	public void save(Schedule schedule) {
		try {
			Session session = getSession();
			session.saveOrUpdate(schedule);
			logger.debug("Updated schedule " + schedule);
		} catch (Exception e) {
			throw new RuntimeException("Failed to save " + schedule, e);
		}
	}

	/* (non-Javadoc)
	 * @see com.tandbergtv.workflow.core.service.Service#getServiceName()
	 */
	public String getServiceName() {
		return "Schedule Persistence";
	}

	/* (non-Javadoc)
	 * @see com.tandbergtv.workflow.core.service.ServiceLifecycle#start()
	 */
	public void start() {
	}

	/* (non-Javadoc)
	 * @see com.tandbergtv.workflow.core.service.ServiceLifecycle#stop()
	 */
	public void stop() {
	}

	private Session getSession() {
		return HibernateContext.getContext().getCurrentSession();
	}
}
