#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/base/thread.h"

using namespace pls::internal;

constexpr size_t NUM_THREADS = 1;

constexpr size_t NUM_TASKS = 128;
constexpr size_t MAX_TASK_STACK_SIZE = 0;

constexpr size_t 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) {
  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};
  });
}

int main() {
  scheduling::static_scheduler_memory<NUM_THREADS,
                                      NUM_TASKS,
                                      MAX_TASK_STACK_SIZE,
                                      NUM_CONTS,
                                      MAX_CONT_SIZE> static_scheduler_memory;

  scheduling::scheduler scheduler{static_scheduler_memory, NUM_THREADS};

  auto start = std::chrono::steady_clock::now();
  std::cout << "fib = " << fib_normal(30) << std::endl;
  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();

  scheduler.perform_work([]() {
    return scheduling::scheduler::par([]() {
      return scheduling::parallel_result<int>(0);
    }, []() {
      return fib(30);
    }).then([](int, int b) {
      std::cout << "fib = " << b << std::endl;
      return scheduling::parallel_result<int>{0};
    });
  });

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

  return 0;
}
