/*
 * 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 org.eclipse.core.databinding.observable.IObservable;
import org.eclipse.core.databinding.observable.set.IObservableSet;
import org.eclipse.core.databinding.observable.value.IObservableValue;

import com.patrikdufresne.managers.ManagerException;
import com.patrikdufresne.managers.databinding.ManagedObjectComputedSet;
import com.planimod.core.PlanimodManagers;
import com.planimod.core.Position;
import com.planimod.core.PositionManager;
import com.planimod.core.Section;

/**
 * This class provide an {@link IObservableSet} < {@link Position} > wrapping
 * the manager function {@link PositionManager#listBySection(Section)} to list
 * all the position for a given section..
 * 
 * @author Patrik Dufresne
 * 
 */
public class PositionBySectionComputedSet extends ManagedObjectComputedSet {

	/**
	 * The observable section.
	 */
	private IObservableValue section;

	/**
	 * Create a new observable set.
	 * 
	 * @param managers
	 *            the managers
	 * @param section
	 *            the observable section
	 */
	public PositionBySectionComputedSet(PlanimodManagers managers,
			IObservableValue section) {
		super(managers, Position.class, new IObservable[] { section });
		this.section = section;
	}

	/**
	 * This implementation list the position for the given section.
	 * 
	 */
	@Override
	protected Collection doList() throws ManagerException {
		if (getSection() == null) {
			return Collections.EMPTY_SET;
		}
		return ((PlanimodManagers) getManagers()).getPositionManager()
				.listBySection(getSection());
	}

	/**
	 * This implementation check if the given element is part of the current
	 * section.
	 */
	@Override
	protected boolean doSelect(Object element) {
		if (getSection() == null) {
			return false;
		}
		return element instanceof Position
				&& ((Position) element).getSection().equals(getSection());
	}

	/**
	 * Return the current section value or null if the observable doesn't
	 * contain a section object.
	 * 
	 * @return the current section or null.
	 */
	protected Section getSection() {
		if (this.section.getValue() instanceof Section) {
			return (Section) this.section.getValue();
		}
		return null;
	}

}
