#include <iostream>
#include <chrono>

#include "pls/internal/scheduling/scheduler.h"
#include "pls/internal/scheduling/parallel_result.h"
#include "pls/internal/scheduling/scheduler_memory.h"
#include "pls/internal/data_structures/bounded_trading_deque.h"

using namespace pls::internal;

constexpr size_t MAX_NUM_THREADS = 1;

constexpr size_t MAX_NUM_TASKS = 128;
static constexpr int NUM_ITERATIONS = 10;

constexpr size_t MAX_NUM_CONTS = 128;
constexpr size_t MAX_CONT_SIZE = 256;

int fib_normal(int n) {
  if (n == 0) {
    return 0;
  }
  if (n == 1) {
    return 1;
  }

  int result = fib_normal(n - 1) + fib_normal(n - 2);
  return result;
}

scheduling::parallel_result<int> fib(int n) {
  pls::variable<int> i;
  pls::array<int> a{10};
  if (n == 0) {
    return 0;
  }
  if (n == 1) {
    return 1;
  }

  return scheduling::scheduler::par([=]() {
    return fib(n - 1);
  }, [=]() {
    return fib(n - 2);
  }).then([=](int a, int b) {
    return scheduling::parallel_result<int>{a + b};
  });
}

static volatile int result;
int main() {
  PROFILE_ENABLE;
  scheduling::static_scheduler_memory<MAX_NUM_THREADS,
                                      MAX_NUM_TASKS,
                                      MAX_NUM_CONTS,
                                      MAX_CONT_SIZE> static_scheduler_memory;

  scheduling::scheduler scheduler{static_scheduler_memory, MAX_NUM_THREADS};

  auto start = std::chrono::steady_clock::now();
  for (int i = 0; i < NUM_ITERATIONS; i++) {
    result = fib_normal(35);
  }
  auto end = std::chrono::steady_clock::now();
  std::cout << "Normal:     " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count()
            << std::endl;

  start = std::chrono::steady_clock::now();

  for (int i = 0; i < NUM_ITERATIONS; i++) {
    scheduler.perform_work([]() {
      PROFILE_MAIN_THREAD;
      return scheduling::scheduler::par([]() {
        return scheduling::parallel_result<int>(0);
      }, []() {
        return fib(35);
      }).then([](int, int b) {
        result = b;
        PROFILE_LOCK("DONE");
        return scheduling::parallel_result<int>{0};
      });
    });
    PROFILE_LOCK("DONE");
  }
  PROFILE_SAVE("test_profile.prof");

  end = std::chrono::steady_clock::now();
  std::cout << "Framework: " << std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() << std::endl;

  return 0;
}
