/**
 * Copyright (C) 2019 Patrik Dufresne Service Logiciel <info@patrikdufresne.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package com.planimod.ui.views.admin.product;

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

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.PlanimodManagers;
import com.planimod.core.Product;
import com.planimod.core.ProductPosition;

public class ProductPositionByProductComputedSet extends ManagedObjectComputedSet {

    protected IObservableValue product;

    public ProductPositionByProductComputedSet(PlanimodManagers managers, IObservableValue product) {
        super(managers, ProductPosition.class, new IObservable[] { product });
        this.product = product;
    }

    @Override
    protected Collection doList() throws ManagerException {
        if (getProduct() == null) {
            return Collections.EMPTY_SET;
        }
        return ((PlanimodManagers) getManagers()).getProductPositionManager().listByProduct(getProduct());
    }

    @Override
    protected boolean doSelect(Object element) {
        if (getProduct() == null) {
            return false;
        }
        return element instanceof ProductPosition && ((ProductPosition) element).getProduct().equals(getProduct());
    }

    protected Product getProduct() {
        if (this.product.getValue() instanceof Product) {
            return (Product) this.product.getValue();
        }
        return null;
    }

}
