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

import java.util.Collection;
import java.util.Collections;
import java.util.Date;

import org.eclipse.core.databinding.observable.IObservable;
import org.eclipse.core.databinding.observable.value.IObservableValue;

import com.patrikdufresne.managers.ManagerException;
import com.patrikdufresne.managers.databinding.ManagedObjectComputedSet;
import com.planimod.core.TimeRanges;
import com.planimod.core.NonAvailabilityManager;
import com.planimod.core.PlanimodManagers;
import com.planimod.core.Shift;

/**
 * This computed set wrap the
 * {@link NonAvailabilityManager#list(java.util.Date, java.util.Date)} .
 * 
 * @author Patrik Dufresne
 * 
 */
public class ShiftComputedSet extends ManagedObjectComputedSet {

	private IObservableValue end;

	private IObservableValue start;

	/**
	 * Create a new computed set.
	 * 
	 * @param managers
	 */
	public ShiftComputedSet(PlanimodManagers managers, IObservableValue start,
			IObservableValue end) {
		super(managers, Shift.class, new IObservable[] { start, end });
		this.start = start;
		this.end = end;
	}

	@Override
	public synchronized void dispose() {
		try{
			this.end = null;
			this.start = null;
		} finally {
			super.dispose();
		}
	}

	/**
	 * This implementation is calling the function
	 * {@link NonAvailabilityManager#list(java.util.Date, java.util.Date)} .
	 */
	@Override
	protected Collection doList() throws ManagerException {
		if (getStart() == null || getEnd() == null) {
			return Collections.EMPTY_SET;
		}
		return ((PlanimodManagers) getManagers()).getShiftManager().list(
				getStart(), getEnd());
	}

	/**
	 * This implementation check if the element is part of a shift calendar
	 * entry and is within the time range.
	 */
	@Override
	protected boolean doSelect(Object element) {
		if (getStart() == null || getEnd() == null) {
			return false;
		}
		return element instanceof Shift
				&& TimeRanges.intersectEquals((Shift) element, getStart(),
						getEnd());
	}

	protected Date getEnd() {
		if (this.end.getValue() instanceof Date) {
			return (Date) this.end.getValue();
		}
		return null;
	}

	protected Date getStart() {
		if (this.start.getValue() instanceof Date) {
			return (Date) this.start.getValue();
		}
		return null;
	}

}
