#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 = 2;

constexpr size_t NUM_TASKS = 64;
constexpr size_t MAX_TASK_STACK_SIZE = 0;

constexpr size_t NUM_CONTS = 64;
constexpr size_t MAX_CONT_SIZE = 256;

std::atomic<int> count{0};
scheduling::parallel_result<int> fib(int n) {
  base::this_thread::sleep(100);
//  std::cout << "Fib(" << n << "): " << count++ << ", " << scheduling::thread_state::get().get_id() << std::endl;
  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) {
    scheduling::parallel_result<int> result{a + b};
    base::this_thread::sleep(100);
//    std::cout << "Done Fib(" << n << "): " << (a + b) << ", " << scheduling::thread_state::get().get_id() << std::endl;
    return result;
  });
}

int fib_normal(int n) {
//  std::cout << "Fib(" << n << "): " << count++ << std::endl;
  if (n == 0) {
    return 0;
  }
  if (n == 1) {
    return 1;
  }

  int result = fib_normal(n - 1) + fib_normal(n - 2);
//  std::cout << "Done Fib(" << n << "): " << result << std::endl;
  return result;
}

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(10) << std::endl;
  auto end = std::chrono::steady_clock::now();
  std::cout << "Normal:     " << std::chrono::duration_cast<std::chrono::microseconds>(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(16);
//    }).then([](int, int b) {
//      std::cout << "fib = " << (b) << std::endl;
//      return scheduling::parallel_result<int>{0};
//    });
    return fib(10);
  });

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

  return 0;
}
