/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.sis.metadata.iso.acquisition;

import java.util.Collection;
import java.util.Date;
import java.time.temporal.Temporal;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import org.opengis.metadata.Identifier;
import org.opengis.metadata.acquisition.Context;
import org.opengis.metadata.acquisition.Event;
import org.opengis.metadata.acquisition.Instrument;
import org.opengis.metadata.acquisition.Objective;
import org.opengis.metadata.acquisition.PlatformPass;
import org.opengis.metadata.acquisition.Sequence;
import org.opengis.metadata.acquisition.Trigger;
import org.apache.sis.metadata.iso.ISOMetadata;
import org.apache.sis.temporal.TemporalDate;

// Specific to the main branch:
import org.opengis.annotation.UML;
import static org.opengis.annotation.Obligation.MANDATORY;
import static org.opengis.annotation.Specification.ISO_19115_2;


/**
 * Identification of a significant collection point within an operation.
 * The following properties are mandatory in a well-formed metadata according ISO 19115:
 *
 * <div class="preformat">{@code MI_Event}
 * {@code   ├─identifier……} Event name or number.
 * {@code   │   └─code…………} Alphanumeric value identifying an instance in the namespace.
 * {@code   ├─trigger……………} Initiator of the event.
 * {@code   ├─context……………} Meaning of the event.
 * {@code   ├─sequence…………} Relative time ordering of the event.
 * {@code   └─time……………………} Time the event occurred.</div>
 *
 * <h2>Limitations</h2>
 * <ul>
 *   <li>Instances of this class are not synchronized for multi-threading.
 *       Synchronization, if needed, is caller's responsibility.</li>
 *   <li>Serialized objects of this class are not guaranteed to be compatible with future Apache SIS releases.
 *       Serialization support is appropriate for short term storage or RMI between applications running the
 *       same version of Apache SIS. For long term storage, use {@link org.apache.sis.xml.XML} instead.</li>
 * </ul>
 *
 * @author  Cédric Briançon (Geomatys)
 * @author  Martin Desruisseaux (Geomatys)
 * @version 1.5
 * @since   0.3
 */
@XmlType(name = "MI_Event_Type", propOrder = {
    "identifier",
    "trigger",
    "context",
    "sequence",
    "dateOfOccurrence",
    "expectedObjectives",
    "relatedPass",
    "relatedSensors"
})
@XmlRootElement(name = "MI_Event")
public class DefaultEvent extends ISOMetadata implements Event {
    /**
     * Serial number for inter-operability with different versions.
     */
    private static final long serialVersionUID = 7862440773058520852L;

    /**
     * Initiator of the event.
     */
    private Trigger trigger;

    /**
     * Meaning of the event.
     */
    private Context context;

    /**
     * Relative time ordering of the event.
     */
    private Sequence sequence;

    /**
     * Date and/or time the event occurred.
     */
    @SuppressWarnings("serial")     // Most implementations are serializable.
    private Temporal time;

    /**
     * Objective or objectives satisfied by an event.
     */
    @SuppressWarnings("serial")
    private Collection<Objective> expectedObjectives;

    /**
     * Pass during which an event occurs.
     */
    @SuppressWarnings("serial")
    private PlatformPass relatedPass;

    /**
     * Instrument or instruments for which the event is meaningful.
     */
    @SuppressWarnings("serial")
    private Collection<Instrument> relatedSensors;

    /**
     * Constructs an initially empty acquisition information.
     */
    public DefaultEvent() {
    }

    /**
     * Constructs a new instance initialized with the values from the specified metadata object.
     * This is a <em>shallow</em> copy constructor, because the other metadata contained in the
     * given object are not recursively copied.
     *
     * @param  object  the metadata to copy values from, or {@code null} if none.
     *
     * @see #castOrCopy(Event)
     */
    public DefaultEvent(final Event object) {
        super(object);
        if (object != null) {
            identifiers        = singleton(object.getIdentifier(), Identifier.class);
            trigger            = object.getTrigger();
            context            = object.getContext();
            sequence           = object.getSequence();
            time               = TemporalDate.toTemporal(object.getTime());
            expectedObjectives = copyCollection(object.getExpectedObjectives(), Objective.class);
            relatedPass        = object.getRelatedPass();
            relatedSensors     = copyCollection(object.getRelatedSensors(), Instrument.class);
        }
    }

    /**
     * Returns a SIS metadata implementation with the values of the given arbitrary implementation.
     * This method performs the first applicable action in the following choices:
     *
     * <ul>
     *   <li>If the given object is {@code null}, then this method returns {@code null}.</li>
     *   <li>Otherwise if the given object is already an instance of
     *       {@code DefaultEvent}, then it is returned unchanged.</li>
     *   <li>Otherwise a new {@code DefaultEvent} instance is created using the
     *       {@linkplain #DefaultEvent(Event) copy constructor} and returned.
     *       Note that this is a <em>shallow</em> copy operation, because the other
     *       metadata contained in the given object are not recursively copied.</li>
     * </ul>
     *
     * @param  object  the object to get as a SIS implementation, or {@code null} if none.
     * @return a SIS implementation containing the values of the given object (may be the
     *         given object itself), or {@code null} if the argument was null.
     */
    public static DefaultEvent castOrCopy(final Event object) {
        if (object == null || object instanceof DefaultEvent) {
            return (DefaultEvent) object;
        }
        return new DefaultEvent(object);
    }

    /**
     * Returns the event name or number.
     *
     * @return event name or number, or {@code null}.
     */
    @Override
    @XmlElement(name = "identifier", required = true)
    public Identifier getIdentifier() {
        return super.getIdentifier();
    }

    /**
     * Sets the event name or number.
     *
     * @param  newValue  the event identifier value.
     */
    @Override
    public void setIdentifier(final Identifier newValue) {
        super.setIdentifier(newValue);
    }

    /**
     * Returns the initiator of the event.
     *
     * @return initiator of the event, or {@code null}.
     */
    @Override
    @XmlElement(name = "trigger", required = true)
    public Trigger getTrigger() {
        return trigger;
    }

    /**
     * Sets the initiator of the event.
     *
     * @param  newValue  the new trigger value.
     */
    public void setTrigger(final Trigger newValue) {
        checkWritePermission(trigger);
        trigger = newValue;
    }

    /**
     * Meaning of the event.
     *
     * @return meaning of the event, or {@code null}.
     */
    @Override
    @XmlElement(name = "context", required = true)
    public Context getContext() {
        return context;
    }

    /**
     * Sets the meaning of the event.
     *
     * @param  newValue  the new context value.
     */
    public void setContext(final Context newValue) {
        checkWritePermission(context);
        context = newValue;
    }

    /**
     * Returns the relative time ordering of the event.
     *
     * @return relative time ordering, or {@code null}.
     */
    @Override
    @XmlElement(name = "sequence", required = true)
    public Sequence getSequence() {
        return sequence;
    }

    /**
     * Sets the relative time ordering of the event.
     *
     * @param  newValue  the new sequence value.
     */
    public void setSequence(final Sequence newValue) {
        checkWritePermission(sequence);
        sequence = newValue;
    }

    /**
     * Returns the time the event occurred.
     *
     * @return time the event occurred, or {@code null}.
     *
     * @deprecated Replaced by {@link #getDateOfOccurrence()}.
     */
    @Override
    @Deprecated(since="1.5")
    public Date getTime() {
        return TemporalDate.toDate(time);
    }

    /**
     * Sets the time the event occurred.
     *
     * @param  newValue  the new time value.
     *
     * @deprecated Replaced by {@link #setDateOfOccurrence(Temporal)}.
     */
    @Deprecated(since="1.5")
    public void setTime(final Date newValue) {
        setDateOfOccurrence(TemporalDate.toTemporal(newValue));
    }

    /**
     * Returns the time the event occurred.
     *
     * @return time the event occurred, or {@code null}.
     *
     * @since 1.5
     */
    @XmlElement(name = "time", required = true)
    @UML(identifier="time", obligation=MANDATORY, specification=ISO_19115_2)
    public Temporal getDateOfOccurrence() {
        return time;
    }

    /**
     * Sets the date and/or time the event occurred.
     *
     * @param  newValue  the new time value.
     *
     * @since 1.5
     */
    public void setDateOfOccurrence(final Temporal newValue) {
        checkWritePermission(time);
        time = newValue;
    }

    /**
     * Returns the objective or objectives satisfied by an event.
     *
     * @return objectives satisfied by an event.
     */
    @Override
    @XmlElement(name = "expectedObjective")
    public Collection<Objective> getExpectedObjectives() {
        return expectedObjectives = nonNullCollection(expectedObjectives, Objective.class);
    }

    /**
     * Sets the objective or objectives satisfied by an event.
     *
     * @param  newValues  the new expected objectives values.
     */
    public void setExpectedObjectives(final Collection<? extends Objective> newValues) {
        expectedObjectives = writeCollection(newValues, expectedObjectives, Objective.class);
    }

    /**
     * Returns the pass during which an event occurs. {@code null} if unspecified.
     *
     * @return pass during which an event occurs, or {@code null}.
     */
    @Override
    @XmlElement(name = "relatedPass")
    public PlatformPass getRelatedPass() {
        return relatedPass;
    }

    /**
     * Sets the pass during which an event occurs.
     *
     * @param  newValue  the new platform pass value.
     */
    public void setRelatedPass(final PlatformPass newValue) {
        relatedPass = newValue;
    }

    /**
     * Returns the instrument or instruments for which the event is meaningful.
     *
     * @return instruments for which the event is meaningful.
     */
    @Override
    @XmlElement(name = "relatedSensor")
    public Collection<? extends Instrument> getRelatedSensors() {
        return relatedSensors = nonNullCollection(relatedSensors, Instrument.class);
    }

    /**
     * Sets the instrument or instruments for which the event is meaningful.
     *
     * @param  newValues  the new instrument values.
     */
    public void setRelatedSensors(final Collection<? extends Instrument> newValues) {
        relatedSensors = writeCollection(newValues, relatedSensors, Instrument.class);
    }
}
