
#ifndef PLS_INTERNAL_SCHEDULING_TASK_TRADING_DEQUE_H_
#define PLS_INTERNAL_SCHEDULING_TASK_TRADING_DEQUE_H_

#include <atomic>
#include <tuple>

#include "pls/internal/base/error_handling.h"
#include "pls/internal/base/system_details.h"

#include "pls/internal/data_structures/optional.h"
#include "pls/internal/data_structures/stamped_integer.h"

#include "pls/internal/scheduling/traded_cas_field.h"
#include "pls/internal/scheduling/task.h"

namespace pls {
namespace internal {
namespace scheduling {

struct trading_deque_entry {
  std::atomic<task *> traded_task_{nullptr};
  std::atomic<unsigned long> forwarding_stamp_{};
};

/**
 * A work stealing deque (single produces/consumer at the end, multiple consumers at the start).
 * A task object can only be acquired by stealing consumers (from the start),
 * when they also offer a task to trade in for it.
 *
 * The exchange of 'goods' (here tasks) happens atomically at a linearization point.
 * This means that the owning thread always gets a tasks for each and every task that was
 * successfully stolen.
 *
 * As each task is associated with memory this suffices to exchange memory blocks needed for execution.
 */
class external_trading_deque {
 public:
  external_trading_deque(trading_deque_entry *entries, size_t num_entries) :
      entries_{entries}, num_entries_{num_entries} {};

  /**
   * Pushes a task on the bottom of the deque.
   * The task itself wil be filled with the unique, synchronizing cas word.
   *
   * @param published_task The task to publish on the bottom of the deque.
   * @return The content of the cas word, can be later used to check if it changed.
   */
  traded_cas_field push_bot(task *published_task) {
    auto expected_stamp = bot_internal_.stamp;
    auto &current_entry = entries_[bot_internal_.value];

    // Store stealing information in the task and deque.
    // Relaxed is fine for this, as adding elements is synced over the bot pointer.
    current_entry.forwarding_stamp_.store(expected_stamp, std::memory_order_relaxed);

    traded_cas_field new_cas_field;
    new_cas_field.fill_with_stamp(expected_stamp, deque_id_);
    published_task->traded_field_.store(new_cas_field, std::memory_order_relaxed);
    current_entry.traded_task_.store(published_task, std::memory_order_relaxed);

    // Advance the bot pointer. Linearization point for making the task public.
    bot_internal_.stamp++;
    bot_internal_.value++;
    bot_.store(bot_internal_.value, std::memory_order_release);

    return new_cas_field;
  }

  void popped_bot() {
    bot_internal_.value--;

    bot_.store(bot_internal_.value, std::memory_order_relaxed);
    if (bot_internal_.value == 0) {
      bot_internal_.stamp++;
      top_.store({bot_internal_.stamp, 0}, std::memory_order_release);
    }
  }

  void empty_deque() {
    bot_internal_.value = 0;
    bot_internal_.stamp++;

    // TODO: We might be able to relax memory orderings...
    bot_.store(bot_internal_.value);
    top_.store(bot_internal_);
  }

  std::tuple<data_structures::optional<task *>, data_structures::stamped_integer> peek_top() {
    auto local_top = top_.load();
    auto local_bot = bot_.load();

    if (local_top.value >= local_bot) {
      return std::make_tuple(data_structures::optional<task *>{}, local_top);
    } else {
      return std::make_tuple(data_structures::optional<task *>{entries_[local_top.value].traded_task_}, local_top);
    }
  }

  data_structures::optional<task *> pop_top(task *trade_offer, data_structures::stamped_integer local_top) {
    auto local_bot = bot_.load();
    if (local_top.value >= local_bot) {
      return data_structures::optional<task *>{};
    }

    unsigned long expected_top_stamp = local_top.stamp;
    auto &target_entry = entries_[local_top.value];

    // Read our potential result
    task *result = target_entry.traded_task_.load(std::memory_order_relaxed);
    unsigned long forwarding_stamp = target_entry.forwarding_stamp_.load(std::memory_order_relaxed);

    // Try to get it by CAS with the expected field entry, giving up our offered_object for it
    traded_cas_field expected_field;
    expected_field.fill_with_stamp(expected_top_stamp, deque_id_);
    traded_cas_field offered_field;
    offered_field.fill_with_trade_object(trade_offer);

    if (result->traded_field_.compare_exchange_strong(expected_field, offered_field, std::memory_order_acq_rel)) {
      // We got it, for sure move the top pointer forward.
      top_.compare_exchange_strong(local_top, {local_top.stamp + 1, local_top.value + 1});
      // Return the stolen task
      return data_structures::optional<task *>{result};
    } else {
      // We did not get it...help forwarding the top pointer anyway.
      if (expected_top_stamp == forwarding_stamp) {
        // ...move the pointer forward if someone else put a valid trade object in there.
        top_.compare_exchange_strong(local_top, {local_top.stamp + 1, local_top.value + 1});
      } else {
        // ...we failed because the top tag lags behind...try to fix it.
        // This means only updating the tag, as this location can still hold data we need.
        top_.compare_exchange_strong(local_top, {forwarding_stamp, local_top.value});
      }
      return data_structures::optional<task *>{};
    }
  }

 private:
  trading_deque_entry *entries_;
  size_t num_entries_;

  unsigned deque_id_;

  alignas(base::system_details::CACHE_LINE_SIZE) std::atomic<data_structures::stamped_integer> top_{{0, 0}};
  alignas(base::system_details::CACHE_LINE_SIZE) std::atomic<size_t> bot_{0};

  data_structures::stamped_integer bot_internal_{0, 0};
};

template<size_t SIZE>
class static_external_trading_deque {
 public:
  static_external_trading_deque() : items_{}, deque_{items_.data(), SIZE} {}

  external_trading_deque &get_deque() { return deque_; }
 private:
  std::array<trading_deque_entry, SIZE> items_;
  external_trading_deque deque_;
};

}
}
}

#endif //PLS_INTERNAL_SCHEDULING_TASK_TRADING_DEQUE_H_
