/*****************************************************************************
 * $CAMITK_LICENCE_BEGIN$
 *
 * CamiTK - Computer Assisted Medical Intervention ToolKit
 * (c) 2001-2025 Univ. Grenoble Alpes, CNRS, Grenoble INP - UGA, TIMC, 38000 Grenoble, France
 *
 * Visit http://camitk.imag.fr for more information
 *
 * This file is part of CamiTK.
 *
 * CamiTK is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * CamiTK 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 version 3 for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with CamiTK.  If not, see <http://www.gnu.org/licenses/>.
 *
 * $CAMITK_LICENCE_END$
 ****************************************************************************/

#ifndef MANAGER_MONITORINGMANAGER_H
#define MANAGER_MONITORINGMANAGER_H

#include <memory>   // std::auto_ptr
#include <vector>

#include <PhysicalModel.h>
#include <Loads.h>

#include <MonitorIn.hxx>
#include <MonitorOut.hxx>

class Monitor;
class Simulator;

#include "MMLAPI.h"
/**
 * @ingroup group_cepmodeling_libraries_mml
 *
 * @brief
 * Manager of the benchmark tests.
 * Do simulation loop and tests
 *
 **/
class MML_API MonitoringManager {
public:

    /**
     * constructor
     *@param mml mml file name
     */
    MonitoringManager(const char* mml);

    /// destructor
    virtual ~MonitoringManager();

    /** Initialize manager
     * @return false if initialisation faild
     */
    virtual bool init() = 0;
    /// End manager
    virtual void end() = 0;

    /// perform simulation loop, make tests and save monitors' data into output file
    void simulate();
    /// Do one step of simulation and save monitors for this step
    virtual void doMove() = 0;
    /// Check if simulation is finished
    virtual bool checkStop() = 0;
    /// Rewind simulation
    void rewind();
    /** reload simulation with current parameters
     * @param delPml true if pml object have to be deleted (perhaps used by others: physicalModel component...)
     */
    void reload(bool delPml = true);

    /// Save save monitors' state for the current time
    void saveMonitors();
    /// Write all saved monitors' states into mmlOut file
    void writeOutput(const char* fileName);
    /// Write all saved monitors'state into csv file
    void writeCsv(const char* fileName);
    /// save current version of mml in
    void saveMmlIn(const char* fileName);

    ///  @name accessors for simulation parameters
    ///@{
    double getDt();
    double getRefresh();
    double getCurrentTime();
    double getCurrentStep();
    double getStepComputingTime();
    double getComputingTime();
    PhysicalModel* getInitPml();
    PhysicalModel* getPml();
    /** This is nearly the same as getPml(), but it also transfers ownership of the pointer.
     *  After this method is called, this instance of MonitoringManager will not delete the pml.
     *  It is then the responsability of the caller (the instance which is taking ownership of the PhysicalModel).
     *  This is useful when transmitting to PMManagerDC Component for example.
     */
    PhysicalModel* takePml();
    Loads* getLml();
    /** This is nearly the same as getLml(), but it also transfers ownership of the pointer.
     *  After this method is called, this instance of MonitoringManager will not delete the pml.
     *  It is then the responsability of the caller (the instance which is taking ownership of the Loads).
     *  This is useful when transmitting to PMManagerDC's Loads manager for example.
     */
    Loads* takeLml();
    std::string getPmlFileName();
    std::string getLmlFileName();
    std::string getMmlFileName();
    std::string getmmlFileFolder();
    Simulator* getSimulator();
    /// get atom position for precedent step
    void getOldPosition(double pos[3], unsigned int index);
    ///@}

    ///mutators for simulation parameters
    void setCurrentTime(double time);

    /// store old positions before next step
    void storeOldPositions();
    /// add dt to current time
    void updateCurrentTime();
    /// add step computing time to total computing time
    void updateComputingTime();
    /// increment step by one
    void incStep();

    ///change dt and save modification into mmlIn
    void setDt(double dt);
    ///change refresh and save modification into mmlIn
    void setRefresh(double refresh);
    ///change pml file name and save modification into mmlIn
    void setPmlFileName(const char* file);
    ///change lml file name and save modification into mmlIn
    void setLmlFileName(const char* file);

    //accessors and mutators for monitors
    /// add a monitor to the list
    void addMonitor(Monitor* monitor);
    /// get a monitor by its index in the list
    Monitor* getMonitor(const unsigned int i) const;
    /// delete a monitor and remove it from the list using its index
    void deleteMonitor(const unsigned int i);
    /// get the number of monitors stored in the list
    unsigned int numberOfMonitor() const;

    /// check if a scn is present instead of pmlFileName
    bool isPmlPresent();
    /// check if a lml is present
    bool isLmlPresent();

protected:

    /// Object representing manager in the file generated by xsdcxx, can be used for serialization
    std::unique_ptr<mml::MonitoringIn> mmlIn;
    /// Vector that contains all monitors
    std::vector<Monitor*> monitors;
    /// Vector that contains information saved by saveMonitors method
    std::vector<mml::TimeStep*> times;

    /// integration step
    double dt;
    /// refreshing step
    double refresh;
    /// name of the simulator
    std::string simulatorName;

    /// current step
    int step;
    /// time at current moment
    double currentTime;
    /// computing time of last step
    double stepComputingTime;
    /// total computing time at current moment
    double computingTime;
    /// the simulator used for simualtion
    Simulator* simul;

private:

    /// build monitors
    void buildMonitors();
    /// build the loads if lml file was given
    void buildLoads();
    /** build physical model and simulator
     * @param delPml true if pml object have to be deleted (perhaps used by others: physicalModel component...)
     */
    void buildPmlAndSimulator(bool delPml = true);
    /// build physical model and simulator from a pml file
    void buildPmlAndSimulatorfromPml();
    /// build physical model and simulator from a specific simulator file
    void buildPmlAndSimulatorfromSimulator();

    /// pml at current moment
    PhysicalModel* pml;
    /// is the pml "own" by this instance, which is the normal case when there are no visual representation. But ownership can also be taken by some other instance, see takePml()
    bool ownPml;
    /// old position pointer
    double* oldPositionPointer;
    /// initial pml
    PhysicalModel* initPml;
    /// Loads applied to pml
    Loads* lml;
    /// is the lml "own" by this is instance, which is the normal case when there are not visual representation. But ownership can also be taken by some other instance, see takeLml()
    bool ownLml;
    /// name of the pml file (complete path from working directory)
    std::string pmlFileName;
    /// name of the lml file (complete path from working directory)
    std::string lmlFileName;
    /// name of the mml in file (complete path from working directory)
    std::string mmlFileName;
    /// folder of mml file (complete path from working directory)
    std::string mmlFileFolder;

};

#endif // MANAGER_MONITORINGMANAGERF_H
