////////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright 2026 OVITO GmbH, Germany
//
//  This file is part of OVITO (Open Visualization Tool).
//
//  OVITO is free software; you can redistribute it and/or modify it either under the
//  terms of the GNU General Public License version 3 as published by the Free Software
//  Foundation (the "GPL") or, at your option, under the terms of the MIT License.
//  If you do not alter this notice, a recipient may use your version of this
//  file under either the GPL or the MIT License.
//
//  You should have received a copy of the GPL along with this program in a
//  file LICENSE.GPL.txt.  You should have received a copy of the MIT License along
//  with this program in a file LICENSE.MIT.txt
//
//  This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
//  either express or implied. See the GPL or the MIT License for the specific language
//  governing rights and limitations.
//
////////////////////////////////////////////////////////////////////////////////////////

#pragma once


#include <ovito/core/Core.h>
#include <ovito/core/utilities/concurrent/Promise.h>
#include <ovito/core/oo/RefTarget.h>
#include <ovito/core/dataset/pipeline/PipelineFlowState.h>
#include <ovito/core/dataset/pipeline/PipelineNode.h>
#include <ovito/core/dataset/pipeline/PipelineCache.h>
#include <ovito/core/dataset/data/DataVis.h>

namespace Ovito {

/**
 * \brief A data pipeline.
 */
class OVITO_CORE_EXPORT Pipeline : public RefTarget
{
    /// Give this class its own metaclass.
    class OVITO_CORE_EXPORT PipelineClass : public RefTarget::OOMetaClass
    {
    public:
        /// Inherit constructor from base class.
        using RefTarget::OOMetaClass::OOMetaClass;

        /// Provides a custom function that takes are of the deserialization of a serialized property field that has been removed or changed in a newer version of OVITO.
        /// This is needed for backward compatibility with OVITO 3.11.
        virtual SerializedPropertyField::CustomDeserializationFunctionPtr overrideFieldDeserialization(LoadStream& stream, const SerializedPropertyField& field) const override;
    };
    OVITO_CLASS_META(Pipeline, PipelineClass)

public:

    /// Custom notification event types generated by this class:
    enum {
        /// This event is generated by a Pipeline when the axis-aligned bounding box of its visual output may have changed.
        BoundingBoxChanged = RefTarget::NEXT_AVAILABLE_EVENT_ID,

        /// End-of-list value indicating the next available event type that can be used by sub-classes for custom notifications.
        NEXT_AVAILABLE_EVENT_ID
    };

#ifdef OVITO_DEBUG
    /// Destructor.
    ~Pipeline();
#endif

    /// Throws an exception if the pipeline stage cannot be evaluated at this time.
    /// This is called by the system to catch user mistakes that would lead to infinite recursion.
    void preEvaluationCheck(const PipelineEvaluationRequest& request) const;

    /// Performs an asynchronous evaluation of the data pipeline.
    [[nodiscard]] PipelineEvaluationResult evaluatePipeline(const PipelineEvaluationRequest& request) {
        return _pipelineCache.evaluatePipeline(request);
    }

    /// Returns the cached output of the data pipeline at the given time if available.
    /// This method will never throw an exception and doesn't require a valid execution context.
    PipelineFlowState getCachedPipelineOutput(AnimationTime time, bool interactiveMode = true) const {
        return _pipelineCache.getAt(time, interactiveMode);
    }

    /// Sets the data source of this pipeline, i.e., the object that provides the
    /// input data entering the pipeline.
    void setSource(PipelineNode* sourceObject);

    /// Applies a modifier by appending a node for it to the pipeline.
    ModificationNode* applyModifier(AnimationTime time, bool interactiveMode, Modifier* modifier);

    /// Returns the title of this object.
    virtual QString objectTitle() const override;

    /// Asks this object to delete itself.
    virtual void requestObjectDeletion() override;

    /// Returns the list of scene nodes that share this pipeline.
    QVector<SceneNode*> sceneNodes() const;

    /// Returns one of the scene nodes referencing this pipeline (if any).
    SceneNode* someSceneNode() const;

    /// Determines  whether this pipeline is currently part of a visualization scene.
    bool isInScene() const;

    /// Rescales the times of all animation keys from the old animation interval to the new interval.
    virtual void rescaleTime(const TimeInterval& oldAnimationInterval, const TimeInterval& newAnimationInterval) override;

    /// Replaces the given visual element in this pipeline's output with an independent copy.
    DataVis* makeVisElementIndependent(DataVis* visElement);

    /// Returns the internal replacement for the given vis element produced by the pipeline.
    /// If there is no replacement, the original vis element is returned.
    DataVis* getReplacementVisElement(DataVis* vis) const;

    /// Replaces all references to the given visual element in the pipeline with new compatible objects.
    void replaceVisualElement(DataVis* visElement, const std::function<OORef<DataVis>(const QString&)>& getReplacement);

    /// Gathers a list of data objects from the given pipeline flow state (which should have been produced by this pipeline)
    /// that are associated with the given vis element. This method takes into account replacement vis elements.
    std::vector<ConstDataObjectPath> getDataObjectsForVisElement(const PipelineFlowState& state, DataVis* vis) const;

    /// Returns the titles of all data objects associated with a visual element produced by this pipeline.
    /// This method only returns a string list after the pipeline has been fully evaluated.
    const QStringList* getDataObjectTitlesForVisElement(DataVis* vis) const;

    /// Computes the axis-aligned bounding box of the pipeline's visual output in local coordinates.
    Box3 localBoundingBox(AnimationTime time, TimeInterval& validity) const;

    /// For backward compatibility with OVITO 3.11:
    /// The Pipeline class has been separated from the SceneNode base class in OVITO 3.12.
    /// A separate SceneNode must now be created when loading an old Pipeline object from a state file.
    /// This function creates and returns the SceneNode for this pipeline object during deserialization of legacy state files.
    OORef<SceneNode>& deserializationSceneNode();

protected:

    /// This method is called when a referenced object has changed.
    virtual bool referenceEvent(RefTarget* source, const ReferenceEvent& event) override;

    /// Is called when the value of a reference field of this object changes.
    virtual void referenceReplaced(const PropertyFieldDescriptor* field, RefTarget* oldTarget, RefTarget* newTarget, int listIndex) override;

    /// Is called when a RefTarget has been added to a VectorReferenceField of this RefMaker.
    virtual void referenceInserted(const PropertyFieldDescriptor* field, RefTarget* newTarget, int listIndex) override;

    /// Is called when a RefTarget has been removed from a VectorReferenceField.
    virtual void referenceRemoved(const PropertyFieldDescriptor* field, RefTarget* oldTarget, int listIndex) override;

    /// Is called when the value of a non-animatable property field of this RefMaker has changed.
    virtual void propertyChanged(const PropertyFieldDescriptor* field) override;

    /// Asks the object to register internal object references that will be saved to a data stream.
    virtual void registerObjectReferencesForSerialization(ObjectSaveStream& stream, const RefTarget* deltaReferenceObject) const override;

    /// Saves the class' contents to the given stream.
    virtual void saveToStream(ObjectSaveStream& stream, bool excludeRecomputableData) const override;

    /// Loads the class' contents from the given stream.
    virtual void loadFromStream(ObjectLoadStream& stream) override;

    /// This method is called once for this object after it has been completely loaded from a stream.
    virtual void loadFromStreamComplete(ObjectLoadStream& stream) override;

private:

    /// Invalidates the contents of the data pipeline cache.
    void invalidatePipelineCache(TimeInterval keepInterval = TimeInterval::empty());

    /// Rebuilds the list of visual elements maintained by the scene node.
    void updateVisElementList(const PipelineFlowState& state);

    /// Determines the current source of the data pipeline and updates the internal weak reference field.
    void updatePipelineSourceReference();

    /// Helper function that recursively collects all visual elements attached to a
    /// data object and its children and stores them in an output vector.
    static void collectVisElements(const DataObject* dataObj, std::vector<std::pair<DataVis*, QStringList>>& visElements);

    /// Helper function that recursively finds all data objects which the given vis element is associated with.
    void collectDataObjectsForVisElement(ConstDataObjectPath& path, DataVis* vis, std::vector<ConstDataObjectPath>& dataObjectPaths) const;

    /// Computes the bounding box of a data object and all its sub-objects.
    void getDataObjectBoundingBox(AnimationTime time, const DataObject* dataObj, const PipelineFlowState& state, TimeInterval& validity, Box3& bb, ConstDataObjectPath& dataObjectPath) const;

private:

    /// The terminal node of the pipeline that generates the data to be rendered in the scene.
    DECLARE_MODIFIABLE_REFERENCE_FIELD(OORef<PipelineNode>, head, setHead);

    /// The transient list of visual elements that render the pipeline's output data objects in the viewports.
    /// This list is for internal caching purposes only and is rebuilt every time the pipeline is newly evaluated.
    DECLARE_VECTOR_REFERENCE_FIELD_FLAGS(OORef<DataVis>, visElements, PROPERTY_FIELD_NEVER_CLONE_TARGET | PROPERTY_FIELD_NO_UNDO | PROPERTY_FIELD_NO_CHANGE_MESSAGE);

    /// List of visual elements coming from the pipeline which shall be replaced with independent versions owned by this pipeline.
    DECLARE_MODIFIABLE_PROPERTY_FIELD_FLAGS(std::vector<OOWeakRef<DataVis>>{}, replacedVisElements, setReplacedVisElements, PROPERTY_FIELD_DONT_SERIALIZE);

    /// Visual elements owned by the pipeline itself, which replace the ones generated within the pipeline.
    DECLARE_VECTOR_REFERENCE_FIELD_FLAGS(OORef<DataVis>, replacementVisElements, PROPERTY_FIELD_NEVER_CLONE_TARGET | PROPERTY_FIELD_NO_CHANGE_MESSAGE | PROPERTY_FIELD_NO_SUB_ANIM);

    /// Activates the precomputation of the pipeline results for all animation frames.
    DECLARE_MODIFIABLE_PROPERTY_FIELD_FLAGS(bool{false}, pipelineTrajectoryCachingEnabled, setPipelineTrajectoryCachingEnabled, PROPERTY_FIELD_NO_UNDO | PROPERTY_FIELD_NO_CHANGE_MESSAGE);

    /// Reference to the pipeline's source node.
    DECLARE_REFERENCE_FIELD_FLAGS(OORef<PipelineNode>, source, PROPERTY_FIELD_NEVER_CLONE_TARGET | PROPERTY_FIELD_NO_CHANGE_MESSAGE | PROPERTY_FIELD_NO_UNDO | PROPERTY_FIELD_NO_SUB_ANIM | PROPERTY_FIELD_DONT_PROPAGATE_MESSAGES);

    /// Enables or disables InteractiveStateAvailable signals from the pipeline in order to refresh the viewports each time partial computation results become available.
    DECLARE_MODIFIABLE_PROPERTY_FIELD_FLAGS(bool{true}, preliminaryUpdatesEnabled, setPreliminaryUpdatesEnabled, PROPERTY_FIELD_NO_UNDO | PROPERTY_FIELD_NO_CHANGE_MESSAGE);

    /// The cached output of the data pipeline (without the effect of visualization elements).
    PipelineCache _pipelineCache{this};

    /// For backward compatibility with OVITO 3.11:
    /// The Pipeline class has been split from the SceneNode base class. A separate SceneNode must now be created when loading a Pipeline from a state file.
    /// This field holds the SceneNode that is automatically being created for this pipeline during serialization of legacy state files.
    OORef<SceneNode> _deserializationSceneNode;

    /// Stores the titles of data objects associated with each visual element.
    std::vector<QStringList> _visElementDataObjectTitles;

    friend class PipelineCache;
};

}   // End of namespace
