/**
 * 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.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;
    }

}
