/**
 * Copyright © CENRA (2016)
 *
 * remi.clement@espaces-naturels.fr
 * 
 * This software is a multi-platform and portable application based on 
 * the scientifical toolbox to monitor wetlands. With this toolbox it’s 
 * possible to calculate indicators «RhoMéO» to monitor quality, 
 * fonctionalities and urban and agricultural pressures of wetlands. 
 * Indicators are calculated using naturalist data entered and/or imported,
 * and geographic data downloaded from a geographic server.
 * 
 * This software is governed by the CeCILL license under French law and
 * abiding by the rules of distribution of free software.  You can  use, 
 * modify and/ or redistribute the software under the terms of the CeCILL
 * license as circulated by CEA, CNRS and INRIA at the following URL
 * "http://www.cecill.info". 
 * 
 * As a counterpart to the access to the source code and  rights to copy,
 * modify and redistribute granted by the license, users are provided only
 * with a limited warranty  and the software's author,  the holder of the
 * economic rights,  and the successive licensors  have only  limited
 * liability. 
 * 
 * In this respect, the user's attention is drawn to the risks associated
 * with loading,  using,  modifying and/or developing or reproducing the
 * software by the user in light of its specific status of free software,
 * that may mean  that it is complicated to manipulate,  and  that  also
 * therefore means  that it is reserved for developers  and  experienced
 * professionals having in-depth computer knowledge. Users are therefore
 * encouraged to load and test the software's suitability as regards their
 * requirements in conditions enabling the security of their systems and/or 
 * data to be ensured and,  more generally, to use and operate it in the 
 * same conditions as regards security. 
 * 
 * The fact that you are presently reading this means that you have had
 * knowledge of the CeCILL license and that you accept its terms.
*/
package fr.cenra.rhomeo.api.data;

import fr.cenra.rhomeo.api.IdentifiedObject;
import fr.cenra.rhomeo.api.InternationalResource;
import fr.cenra.rhomeo.core.RhomeoCore;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.time.LocalDate;
import java.util.Collection;
import java.util.Collections;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import org.apache.sis.util.ArgumentChecks;

/**
 * A point on which a series of statements have been done. The point is
 * identified by a name and the year on which statements have been done.
 *
 * It's an (almost) immutable object, because its just a reflection of
 * statements name and date property, to use grouping. Moreover, introducing
 * points with null year would be problematic for computing work flow. The only
 * editable attribute is the remarks property, as it's not a defining data.
 *
 * @author Alexis Manin (Geomatys)
 */
public final class TrackingPoint implements IdentifiedObject, InternationalResource, Externalizable {

    protected static final long serialVersionUID = 1L;

    private String name;

    private int year;

    private LocalDate yearStart;
    private LocalDate yearEnd;

    private final StringProperty remarks;

    public TrackingPoint() {
        this("default", 2016);
    }

    public TrackingPoint(final String name, final int year) {
        this(name, year, null, null);
    }

    public TrackingPoint(final String name, final LocalDate yearStart, final LocalDate yearEnd) {
        this(
                name,
                // Try to find a valid year from input dates.
                yearEnd != null ? yearEnd.getYear() : yearStart != null ? yearStart.getYear() : LocalDate.now().getYear(),
                yearStart,
                yearEnd
        );
    }

    public TrackingPoint(String name, final int year, LocalDate yearStart, LocalDate yearEnd) {
        if (name == null || (name = name.trim()).isEmpty()) {
            throw new IllegalArgumentException("Given name is blank !");
        }
        this.name = name;
        this.remarks = new SimpleStringProperty();

        if (yearStart == null) {
            if (yearEnd != null) {
                yearStart = yearEnd.minusYears(1).plusDays(1);
            } else {
                yearStart = LocalDate.of(year, 01, 01);
            }
        }

        if (yearEnd == null) {
            yearEnd = yearStart.plusYears(1).minusDays(1);
        }

        if (yearStart.isBefore(yearEnd)) {
            this.yearStart = yearStart;
            this.yearEnd = yearEnd;
        } else {
            this.yearStart = yearEnd;
            this.yearEnd = yearStart;
        }

        ArgumentChecks.ensureBetween("Year", this.yearStart.getYear(), this.yearEnd.getYear(), year);
        this.year = year;
    }

    /**
     *
     * @return Year associated to this point.
     */
    public int getYear() {
        return year;
    }

    @Override
    public int hashCode() {
        int hash = 5;
        hash = 71 * hash + this.year;
        hash = 71 * hash + this.name.hashCode();
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final TrackingPoint other = (TrackingPoint) obj;
        return this.year == other.year && this.name.equals(other.name);
    }

    @Override
    public String toString() {
        return new StringBuilder("TrackingPoint{ name=").append(name).append(" year=").append(year).append(" }").toString();
    }

    public LocalDate getYearStart() {
        return yearStart;
    }

    public LocalDate getYearEnd() {
        return yearEnd;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getRemarks() {
        return remarks.get();
    }

    public void setRemarks(String remarks) {
        this.remarks.set(remarks);
    }

    public StringProperty remarksProperty() {
        return remarks;
    }

    @Override
    public Collection<String> getAlias() {
        return Collections.EMPTY_SET;
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(name);
        out.writeInt(year);
        RhomeoCore.writeDate(yearStart, out);
        RhomeoCore.writeDate(yearEnd, out);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name = in.readUTF();
        year = in.readInt();
        yearStart = RhomeoCore.readDate(in);
        yearEnd = RhomeoCore.readDate(in);
    }
}
