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

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.PlanimodManagers;
import com.planimod.core.ProductionEvent;
import com.planimod.core.ProductionEventManager;

/**
 * This computed set wrap the function
 * {@link ProductionEventManager#listProductionEvents(com.planimod.core.Planif, java.util.Date, java.util.Date)}
 * .
 * 
 * @author Patrik Dufresne
 * 
 */
public class ProductionEventComputedSet extends ManagedObjectComputedSet {

	private IObservableValue end;

	private IObservableValue start;

	public ProductionEventComputedSet(PlanimodManagers managers,
			IObservableValue start, IObservableValue end) {
		super(managers, ProductionEvent.class, new IObservable[] { start, end });
		this.start = start;
		this.end = end;
	}

	@Override
	protected Collection doList() throws ManagerException {
		if (getStart() == null || getEnd() == null) {
			return Collections.EMPTY_SET;
		}
		return ((PlanimodManagers) getManagers()).getProductionEventManager()
				.list(getStart(), getEnd());
	}

	@Override
	protected boolean doSelect(Object element) {
		if (getStart() == null || getEnd() == null) {
			return false;
		}
		return element instanceof ProductionEvent
				&& TimeRanges.intersectEquals(
						((ProductionEvent) element).getShift(), 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;
	}

}
