#ifndef PLS_BASE_TASK_H
#define PLS_BASE_TASK_H

#include <utility>
#include <atomic>

#include "context_switcher/continuation.h"
#include "context_switcher/context_switcher.h"

namespace pls::internal::scheduling {
/**
 * A task is the smallest unit of execution seen by the runtime system.
 *
 * Tasks represent a action dispatched by a potentially parallel call.
 * Tasks have their own execution context (stack and register state), making them stackefull coroutines.
 * Tasks can be suspended and resumed (stealing happens by resuming a task).
 *
 * Being coroutines tasks go through a very deliberate state machine:
 * - initialized (no execution state)
 * - running (currently executing user code)
 * - suspended (suspended by switching to a different task).
 *
 * This base_task can be extended by different trading/stealing implementations,
 * to add for example additional flags. The scheduler itself always works solely with this base version.
 */
struct base_task {
  base_task(char *stack_memory, size_t stack_size, unsigned depth, unsigned thread_id) :
      depth_{depth},
      thread_id_{thread_id},
      stack_memory_{stack_memory},
      stack_size_{stack_size},
      is_synchronized_{false},
      prev_{nullptr},
      next_{nullptr} {}

  // Do not allow accidental copy/move operations.
  // The whole runtime relies on tasks never changing memory positions during execution.
  // Create tasks ONCE and use them until the runtime is shut down.
  base_task(const base_task &other) = delete;
  base_task(base_task &&other) = delete;
  base_task &operator=(const base_task &other) = delete;
  base_task &operator=(base_task &&other) = delete;

  template<typename F>
  context_switcher::continuation run_as_task(F &&lambda) {
    return context_switcher::enter_context(stack_memory_, stack_size_, std::forward<F>(lambda));
  }

  // General task information
  unsigned depth_;
  unsigned thread_id_;

  // Stack/continuation management
  char *stack_memory_;
  size_t stack_size_;
  context_switcher::continuation continuation_;
  bool is_synchronized_;

  // Linked list for trading/memory management
  base_task *prev_;
  base_task *next_;
};

}

#endif //PLS_BASE_TASK_H
