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

import java.util.Date;

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

import com.patrikdufresne.jface.databinding.value.ComputedObservableValue;
import com.planimod.core.ConcreteTimeRange;
import com.planimod.core.TimeRange;

/**
 * Compute the value of a TimeRange from two observable date: start and end.
 * 
 * @author Patrik Dufresne
 * 
 */
public class ComputedObservableTimeRange extends ComputedObservableValue {

    private IObservableValue start;
    private IObservableValue end;

    /**
     * Create a new instance of this class.
     * 
     * @param start
     *            the observable start date
     * @param end
     *            the observable end date
     */
    public ComputedObservableTimeRange(IObservableValue start, IObservableValue end) {
        this(Realm.getDefault(), start, end);
    }

    /**
     * Create a new instance of this class.
     * 
     * @param realm
     *            the realm
     * @param start
     *            the observable start date
     * @param end
     *            the observable end date
     */
    public ComputedObservableTimeRange(Realm realm, IObservableValue start, IObservableValue end) {
        super(realm, TimeRange.class, start, end);
        this.start = start;
        this.end = end;
    }

    /**
     * This implementation create a new instance of a time range using the value of the observable start date and end
     * date.
     */
    @Override
    protected Object calculate() {
        if (!(this.start.getValue() instanceof Date) || !(this.end.getValue() instanceof Date)) {
            return null;
        }
        Date s = (Date) this.start.getValue();
        Date e = (Date) this.end.getValue();
        return new ConcreteTimeRange(s, e);
    }

}
