
#ifndef PLS_LOCK_FREE_TASK_MANAGER_H_
#define PLS_LOCK_FREE_TASK_MANAGER_H_

#include <memory>
#include <utility>
#include <array>

#include "pls/internal/base/stack_allocator.h"

#include "pls/internal/scheduling/lock_free/task.h"
#include "pls/internal/scheduling/lock_free/external_trading_deque.h"

namespace pls::internal::scheduling {
struct thread_state;
}

namespace pls::internal::scheduling::lock_free {

/**
 * Handles management of tasks in the system. Each thread has a local task manager,
 * responsible for allocating, freeing and publishing tasks for stealing.
 *
 * All interaction for spawning, stealing and task trading are managed through this class.
 */
class task_manager {
  using stack_allocator = pls::internal::base::stack_allocator;

 public:
  explicit task_manager(unsigned thread_id,
                        size_t num_tasks,
                        size_t stack_size,
                        std::shared_ptr<stack_allocator> &stack_allocator);
  ~task_manager();

  task *get_task(size_t index) { return tasks_[index].get(); }

  // Local scheduling
  void push_local_task(base_task *pushed_task);
  base_task *pop_local_task();

  // Stealing work, automatically trades in another task
  base_task *steal_task(thread_state &stealing_state);

  // Sync/memory management
  base_task *pop_clean_task_chain(base_task *task);
 private:
  // Internal helpers for resource stack on tasks
  void push_resource_on_task(task *target_task, task *spare_task_chain);
  task *pop_resource_from_task(task *target_task);

  std::shared_ptr<stack_allocator> stack_allocator_;
  std::vector<std::unique_ptr<task>> tasks_;

  external_trading_deque deque_;
};
}

#endif //PLS_LOCK_FREE_TASK_MANAGER_H_
