#include "pls/internal/helpers/profiler.h"

#include "pls/internal/scheduling/scheduler.h"
#include "pls/internal/scheduling/task.h"
#include "pls/internal/scheduling/thread_state.h"

namespace pls {
namespace internal {
namespace scheduling {

task::task() :
    ref_count_{0},
    parent_{nullptr},
    deque_state_{0} {}

task::task(const task &other) :
    ref_count_{0},
    parent_{other.parent_},
    deque_state_{other.deque_state_} {}

void task::execute() {
  {
    PROFILE_WORK_BLOCK("execute task")
    auto last_executing = thread_state::get()->current_task_;
    thread_state::get()->current_task_ = this;

    execute_internal();

    thread_state::get()->current_task_ = last_executing;
  }

  wait_for_all();

  if (parent_ != nullptr) {
    parent_->ref_count_--;
  }
}

void task::wait_for_all() {
  auto scheduler = thread_state::get()->scheduler_;

  while (ref_count_ > 0) {
    if (!scheduler->try_execute_local()) {
      scheduler->try_execute_stolen();
    }
  }
  thread_state::get()->deque_.release_memory_until(deque_state_);
}

}
}
}
