#include "pls/internal/scheduling/scheduler_memory.h"

namespace pls {
namespace internal {
namespace scheduling {

malloc_scheduler_memory::malloc_scheduler_memory(const size_t num_threads, const size_t memory_per_stack) :
    num_threads_{num_threads} {
  threads_ =
      reinterpret_cast<aligned_thread *>(base::alignment::allocate_aligned(num_threads * sizeof(aligned_thread)));
  thread_states_ = reinterpret_cast<aligned_thread_state *>(base::alignment::allocate_aligned(
      num_threads * sizeof(aligned_thread_state)));
  task_stacks_ = reinterpret_cast<aligned_aligned_stack *>(base::alignment::allocate_aligned(
      num_threads * sizeof(aligned_aligned_stack)));
  task_stacks_memory_ = reinterpret_cast<char **>(base::alignment::allocate_aligned(num_threads * sizeof(char *)));

  thread_refs_ = static_cast<scheduler_thread **>(malloc(num_threads * sizeof(scheduler_thread *)));
  thread_state_refs_ = static_cast<thread_state **>(malloc(num_threads * sizeof(thread_state *)));
  task_stack_refs_ =
      static_cast<data_structures::aligned_stack **>(malloc(num_threads * sizeof(data_structures::aligned_stack *)));

  for (size_t i = 0; i < num_threads_; i++) {
    task_stacks_memory_[i] = reinterpret_cast<char *>(base::alignment::allocate_aligned(memory_per_stack));
    new((void *) task_stacks_[i].pointer()) data_structures::aligned_stack(task_stacks_memory_[i], memory_per_stack);

    thread_refs_[i] = threads_[i].pointer();
    thread_state_refs_[i] = thread_states_[i].pointer();
    task_stack_refs_[i] = task_stacks_[i].pointer();
  }

  init(num_threads, thread_state_refs_, thread_refs_, task_stack_refs_);
}

malloc_scheduler_memory::~malloc_scheduler_memory() {
  free(threads_);
  free(thread_states_);

  for (size_t i = 0; i < num_threads_; i++) {
    free(task_stacks_memory_[i]);
  }
  free(task_stacks_);
  free(task_stacks_memory_);

  free(thread_refs_);
  free(thread_state_refs_);
  free(task_stack_refs_);
}

}
}
}
