/* Copyright (c) 2004-2017. The SimGrid Team. All rights reserved.          */

/* This program is free software; you can redistribute it and/or modify it
 * under the terms of the license (GNU LGPL) which comes with this package. */

#ifndef SURF_MODEL_H_
#define SURF_MODEL_H_

#include "xbt/signal.hpp"
#include "xbt/utility.hpp"

#include "src/surf/surf_private.hpp"
#include "surf/surf.hpp"
#include "xbt/str.h"

#include <boost/heap/pairing_heap.hpp>
#include <boost/intrusive/list.hpp>
#include <boost/optional.hpp>
#include <cmath>
#include <set>
#include <string>
#include <unordered_map>

#define NO_MAX_DURATION -1.0

/*********
 * Utils *
 *********/

/* user-visible parameters */
XBT_PUBLIC_DATA(double) sg_maxmin_precision;
XBT_PUBLIC_DATA(double) sg_surf_precision;
XBT_PUBLIC_DATA(int) sg_concurrency_limit;

extern XBT_PRIVATE double sg_tcp_gamma;
extern XBT_PRIVATE double sg_latency_factor;
extern XBT_PRIVATE double sg_bandwidth_factor;
extern XBT_PRIVATE double sg_weight_S_parameter;
extern XBT_PRIVATE int sg_network_crosstraffic;
extern XBT_PRIVATE std::vector<std::string> surf_path;
extern XBT_PRIVATE std::unordered_map<std::string, tmgr_trace_t> traces_set_list;
extern XBT_PRIVATE std::set<std::string> watched_hosts;

static inline void double_update(double* variable, double value, double precision)
{
  // printf("Updating %g -= %g +- %g\n",*variable,value,precision);
  // xbt_assert(value==0  || value>precision);
  // Check that precision is higher than the machine-dependent size of the mantissa. If not, brutal rounding  may
  // happen, and the precision mechanism is not active...
  // xbt_assert(*variable< (2<<DBL_MANT_DIG)*precision && FLT_RADIX==2);
  *variable -= value;
  if (*variable < precision)
    *variable = 0.0;
}

static inline int double_positive(double value, double precision)
{
  return (value > precision);
}

static inline int double_equals(double value1, double value2, double precision)
{
  return (fabs(value1 - value2) < precision);
}

extern "C" {
XBT_PUBLIC(double) surf_get_clock();
}
/** \ingroup SURF_simulation
 *  \brief List of hosts that have just restarted and whose autorestart process should be restarted.
 */
XBT_PUBLIC_DATA(std::vector<sg_host_t>) host_that_restart;

namespace simgrid {
namespace surf {

extern XBT_PRIVATE simgrid::xbt::signal<void()> surfExitCallbacks;
}
}

int XBT_PRIVATE __surf_is_absolute_file_path(const char *file_path);

/***********
 * Classes *
 ***********/

enum heap_action_type{
  LATENCY = 100,
  MAX_DURATION,
  NORMAL,
  NOTSET
};

/**********
 * Action *
 **********/

/** \ingroup SURF_models
 *  \brief List of initialized models
 */
XBT_PUBLIC_DATA(std::vector<surf_model_t>*) all_existing_models;

namespace simgrid {
namespace surf {

typedef std::pair<double, simgrid::surf::Action*> heap_element_type;
typedef boost::heap::pairing_heap<heap_element_type, boost::heap::constant_time_size<false>, boost::heap::stable<true>,
                                  boost::heap::compare<simgrid::xbt::HeapComparator<heap_element_type>>>
    heap_type;

/** @ingroup SURF_interface
 * @brief SURF action interface class
 * @details An action is an event generated by a resource (e.g.: a communication for the network)
 */
XBT_PUBLIC_CLASS Action {
public:
  boost::intrusive::list_member_hook<> action_hook;
  boost::intrusive::list_member_hook<> action_lmm_hook;
  typedef boost::intrusive::member_hook<
    Action, boost::intrusive::list_member_hook<>, &Action::action_hook> ActionOptions;
  typedef boost::intrusive::list<Action, ActionOptions> ActionList;

  enum class State {
    ready = 0,        /**< Ready        */
    running,          /**< Running      */
    failed,           /**< Task Failure */
    done,             /**< Completed    */
    to_free,          /**< Action to free in next cleanup */
    not_in_the_system /**< Not in the system anymore. Why did you ask ? */
  };

  /**
   * @brief Action constructor
   *
   * @param model The Model associated to this Action
   * @param cost The cost of the Action
   * @param failed If the action is impossible (e.g.: execute something on a switched off host)
   */
  Action(simgrid::surf::Model* model, double cost, bool failed);

  /**
   * @brief Action constructor
   *
   * @param model The Model associated to this Action
   * @param cost The cost of the Action
   * @param failed If the action is impossible (e.g.: execute something on a switched off host)
   * @param var The lmm variable associated to this Action if it is part of a LMM component
   */
  Action(simgrid::surf::Model* model, double cost, bool failed, lmm_variable_t var);

  /** @brief Destructor */
  virtual ~Action();

  /**
   * @brief Mark that the action is now finished
   *
   * @param state the new [state](\ref simgrid::surf::Action::State) of the current Action
   */
  void finish(Action::State state);

  /** @brief Get the [state](\ref simgrid::surf::Action::State) of the current Action */
  Action::State getState() const; /**< get the state*/
  /** @brief Set the [state](\ref simgrid::surf::Action::State) of the current Action */
  virtual void setState(Action::State state);

  /** @brief Get the bound of the current Action */
  double getBound() const;
  /** @brief Set the bound of the current Action */
  void setBound(double bound);

  /** @brief Get the start time of the current action */
  double getStartTime() const { return start_; }
  /** @brief Get the finish time of the current action */
  double getFinishTime() const { return finishTime_; }

  /** @brief Get the user data associated to the current action */
  void* getData() const { return data_; }
  /** @brief Set the user data associated to the current action */
  void setData(void* data) { data_ = data; }

  /** @brief Get the cost of the current action */
  double getCost() const { return cost_; }
  /** @brief Set the cost of the current action */
  void setCost(double cost) {cost_ = cost;}

  /** @brief Update the maximum duration of the current action
   *  @param delta Amount to remove from the MaxDuration */
  void updateMaxDuration(double delta) {double_update(&maxDuration_, delta,sg_surf_precision);}

  /** @brief Update the remaining time of the current action
   *  @param delta Amount to remove from the remaining time */
  void updateRemains(double delta) {double_update(&remains_, delta, sg_maxmin_precision*sg_surf_precision);}

  /** @brief Set the remaining time of the current action */
  void setRemains(double value) {remains_ = value;}
  /** @brief Get the remaining time of the current action after updating the resource */
  virtual double getRemains();
  /** @brief Get the remaining time of the current action without updating the resource */
  double getRemainsNoUpdate() const { return remains_; }

  /** @brief Set the finish time of the current action */
  void setFinishTime(double value) {finishTime_ = value;}

  /**@brief Add a reference to the current action (refcounting) */
  void ref();
  /** @brief Unref that action (and destroy it if refcount reaches 0)
   *  @return true if the action was destroyed and false if someone still has references on it
   */
  virtual int unref();

  /** @brief Cancel the current Action if running */
  virtual void cancel();

  /** @brief Suspend the current Action */
  virtual void suspend();

  /** @brief Resume the current Action */
  virtual void resume();

  /** @brief Returns true if the current action is running */
  virtual bool isSuspended();

  /** @brief Get the maximum duration of the current action */
  double getMaxDuration() const { return maxDuration_; }
  /** @brief Set the maximum duration of the current Action */
  virtual void setMaxDuration(double duration);

  /** @brief Get the tracing category associated to the current action */
  char* getCategory() const { return category_; }
  /** @brief Set the tracing category of the current Action */
  void setCategory(const char *category);

  /** @brief Get the priority of the current Action */
  double getPriority() const { return sharingWeight_; };
  /** @brief Set the priority of the current Action */
  virtual void setSharingWeight(double priority);
  void setSharingWeightNoUpdate(double weight) { sharingWeight_ = weight; }

  /** @brief Get the state set in which the action is */
  ActionList* getStateSet() const { return stateSet_; };

  simgrid::surf::Model* getModel() const { return model_; }

protected:
  ActionList* stateSet_;
  int    refcount_ = 1;

private:
  double sharingWeight_ = 1.0;             /**< priority (1.0 by default) */
  double maxDuration_ = NO_MAX_DURATION; /*< max_duration (may fluctuate until the task is completed) */
  double remains_;                       /**< How much of that cost remains to be done in the currently running task */
  double start_; /**< start time  */
  char *category_ = nullptr;            /**< tracing category for categorized resource utilization monitoring */
  double finishTime_ =
      -1; /**< finish time : this is modified during the run and fluctuates until the task is completed */

  double    cost_;
  simgrid::surf::Model *model_;
  void *data_ = nullptr; /**< for your convenience */

  /* LMM */
  double lastUpdate_                                  = 0;
  double lastValue_                                   = 0;
  lmm_variable_t variable_                            = nullptr;
  enum heap_action_type hat_                          = NOTSET;
  boost::optional<heap_type::handle_type> heapHandle_ = boost::none;

public:
  virtual void updateRemainingLazy(double now) { THROW_IMPOSSIBLE; };
  void heapInsert(heap_type& heap, double key, enum heap_action_type hat);
  void heapRemove(heap_type& heap);
  void heapUpdate(heap_type& heap, double key, enum heap_action_type hat);
  void clearHeapHandle() { heapHandle_ = boost::none; }
  lmm_variable_t getVariable() const { return variable_; }
  void setVariable(lmm_variable_t var) { variable_ = var; }
  double getLastUpdate() const { return lastUpdate_; }
  void refreshLastUpdate() {lastUpdate_ = surf_get_clock();}
  double getLastValue() const { return lastValue_; }
  void setLastValue(double val) { lastValue_ = val; }
  enum heap_action_type getHat() const { return hat_; }
  bool is_linked() const { return action_lmm_hook.is_linked(); }
protected:
  int suspended_ = 0;
};

typedef Action::ActionList ActionList;

typedef boost::intrusive::member_hook<
  Action, boost::intrusive::list_member_hook<>, &Action::action_lmm_hook> ActionLmmOptions;
typedef boost::intrusive::list<Action, ActionLmmOptions> ActionLmmList;
typedef ActionLmmList* ActionLmmListPtr;

/*********
 * Model *
 *********/

/** @ingroup SURF_interface
 * @brief SURF model interface class
 * @details A model is an object which handle the interactions between its Resources and its Actions
 */
XBT_PUBLIC_CLASS Model {
public:
  Model();
  virtual ~Model();

  /** @brief Get the set of [actions](@ref Action) in *ready* state */
  virtual ActionList* getReadyActionSet() const { return readyActionSet_; }

  /** @brief Get the set of [actions](@ref Action) in *running* state */
  virtual ActionList* getRunningActionSet() const { return runningActionSet_; }

  /** @brief Get the set of [actions](@ref Action) in *failed* state */
  virtual ActionList* getFailedActionSet() const { return failedActionSet_; }

  /** @brief Get the set of [actions](@ref Action) in *done* state */
  virtual ActionList* getDoneActionSet() const { return doneActionSet_; }

  /** @brief Get the set of modified [actions](@ref Action) */
  virtual ActionLmmListPtr getModifiedSet() const { return modifiedSet_; }

  /** @brief Get the maxmin system of the current Model */
  lmm_system_t getMaxminSystem() const { return maxminSystem_; }

  /**
   * @brief Get the update mechanism of the current Model
   * @see e_UM_t
   */
  e_UM_t getUpdateMechanism() const { return updateMechanism_; }
  void setUpdateMechanism(e_UM_t mechanism) { updateMechanism_ = mechanism; }

  /** @brief Get Action heap */
  heap_type& getActionHeap() { return actionHeap_; }

  double actionHeapTopDate() const { return actionHeap_.top().first; }
  Action* actionHeapPop();
  bool actionHeapIsEmpty() const { return actionHeap_.empty(); }

  /**
   * @brief Share the resources between the actions
   *
   * @param now The current time of the simulation
   * @return The delta of time till the next action will finish
   */
  virtual double nextOccuringEvent(double now);
  virtual double nextOccuringEventLazy(double now);
  virtual double nextOccuringEventFull(double now);

  /**
   * @brief Update action to the current time
   *
   * @param now The current time of the simulation
   * @param delta The delta of time since the last update
   */
  virtual void updateActionsState(double now, double delta);
  virtual void updateActionsStateLazy(double now, double delta);
  virtual void updateActionsStateFull(double now, double delta);

  /** @brief Returns whether this model have an idempotent shareResource()
   *
   * The only model that is not is NS3: computing the next timestamp moves the model up to that point,
   * so we need to call it only when the next timestamp of other sources is computed.
   */
  virtual bool nextOccuringEventIsIdempotent() { return true;}

protected:
  ActionLmmListPtr modifiedSet_;
  lmm_system_t maxminSystem_ = nullptr;
  bool selectiveUpdate_;

private:
  e_UM_t updateMechanism_ = UM_UNDEFINED;
  ActionList* readyActionSet_; /**< Actions in state SURF_ACTION_READY */
  ActionList* runningActionSet_; /**< Actions in state SURF_ACTION_RUNNING */
  ActionList* failedActionSet_; /**< Actions in state SURF_ACTION_FAILED */
  ActionList* doneActionSet_; /**< Actions in state SURF_ACTION_DONE */
  heap_type actionHeap_;
};

}
}

/************
 * Resource *
 ************/

/** @ingroup SURF_interface
 * @brief Resource which have a metric handled by a maxmin system
 */
struct s_surf_metric_t {
  double peak;              /**< The peak of the metric, ie its max value */
  double scale;             /**< Current availability of the metric according to the traces, in [0,1] */
  tmgr_trace_event_t event; /**< The associated trace event associated to the metric */
};

namespace simgrid {
namespace surf {

/** @ingroup SURF_interface
 * @brief SURF resource interface class
 * @details This is the ancestor class of every resources in SimGrid, such as links, CPU or storage
 */
XBT_PUBLIC_CLASS Resource {
public:
  /**
   * @brief Constructor of LMM Resources
   *
   * @param model Model associated to this Resource
   * @param name The name of the Resource
   * @param constraint The lmm constraint associated to this Resource if it is part of a LMM component
   */
  Resource(Model * model, const std::string& name, lmm_constraint_t constraint);

  virtual ~Resource();

  /** @brief Get the Model of the current Resource */
  Model* model() const;

  /** @brief Get the name of the current Resource */
  const std::string& getName() const;
  /** @brief Get the name of the current Resource */
  const char* getCname() const;

  bool operator==(const Resource &other) const;

  /**
   * @brief Apply an event of external load event to that resource
   *
   * @param event What happened
   * @param value [TODO]
   */
  virtual void apply_event(tmgr_trace_event_t event, double value) = 0;

  /** @brief Check if the current Resource is used (if it currently serves an action) */
  virtual bool isUsed()=0;

  /** @brief returns the current load (in flops per second, byte per second or similar) */
  virtual double getLoad();

  /** @brief Check if the current Resource is active */
  virtual bool isOn() const;
  /** @brief Check if the current Resource is shut down */
  virtual bool isOff() const;
  /** @brief Turn on the current Resource */
  virtual void turnOn();
  /** @brief Turn off the current Resource */
  virtual void turnOff();

private:
  std::string name_;
  Model *model_;
  bool isOn_ = true;

public: /* LMM */
  /** @brief Get the lmm constraint associated to this Resource if it is part of a LMM component (or null if none) */
  lmm_constraint_t constraint() const;

protected:
  const lmm_constraint_t constraint_ = nullptr;
};

}
}

namespace std {
template <> class hash<simgrid::surf::Resource> {
public:
  std::size_t operator()(const simgrid::surf::Resource& r) const { return (std::size_t)xbt_str_hash(r.getCname()); }
};
}

#endif /* SURF_MODEL_H_ */
