/*
 * Copyright (c) 2011, Patrik Dufresne. All rights reserved.
 * Patrik Dufresne PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.planimod.ui.views.planif;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;

import com.patrikdufresne.managers.ManagerException;
import com.patrikdufresne.managers.databinding.ManagedObjectComputedSet;
import com.planimod.core.GeneratePlanifContext;
import com.planimod.core.NonAvailabilityManager;
import com.planimod.core.Task;
import com.planimod.core.TaskManager;
import com.planimod.ui.PlanimodPolicy;

/**
 * This computed set is used to wrap the function
 * {@link NonAvailabilityManager#listProductionEvents(Planif, Date, Date)} and
 * make it observable.
 * 
 */
public class TaskComputedSet extends ManagedObjectComputedSet {

	private GeneratePlanifContext context;

	/**
	 * Property change listener.
	 */
	private PropertyChangeListener listener = new PropertyChangeListener() {
		@Override
		public void propertyChange(PropertyChangeEvent evt) {
			getRealm().exec(new Runnable() {
				@Override
				public void run() {
					makeDirty();
				}
			});
		}
	};
	
	/**
	 * Create an observable set.
	 * 
	 * @param managers
	 *            the managers to use
	 * @param planif
	 *            the planif observable
	 * @param start
	 *            the start date observable
	 * @param end
	 *            the end date observable
	 * @return the observable set
	 */
	public TaskComputedSet(GeneratePlanifContext context) {
		super(context.getManagers(), Task.class);
		this.context = context;
	}

	/**
	 * This implementation run the
	 * {@link TaskManager#listByPlanif(Planif, Date, Date) }. function.
	 */
	@Override
	protected Collection doList() throws ManagerException {
		try {
			return this.context.listTask();
		} catch (Exception e) {
			PlanimodPolicy.showException(e);
			return Collections.EMPTY_SET;
		}
	}

	@Override
	protected void makeDirty() {
		super.makeDirty();
	}

	@Override
	protected void startListening() {
		super.startListening();
		this.context.addPropertyChangeListener(
				GeneratePlanifContext.LIST_TASK_BY_EMPLOYEE, this.listener);
	}

	@Override
	protected void stopListening() {
		super.stopListening();
		this.context.removePropertyChangeListener(
				GeneratePlanifContext.LIST_TASK_BY_EMPLOYEE, this.listener);
	}

}