#pragma once

#include "vector.hpp"
#include <chrono>
#include <print>
#include <ranges>
#include <string>
#include <thread>

namespace workers {
void writer(th_safe::vector<std::string> &news_vector,
            std::int32_t count = 10) {
  for (std::int32_t i : std::views::iota(0, count)) {
    std::this_thread::sleep_for(std::chrono::milliseconds(200));

    auto news = std::format("News item {}", i + 1);
    news_vector.push_back(news);
    std::print("Writer: added '{}'\n", news);
  }
}

void reader(const th_safe::vector<std::string> &news_vector,
            std::atomic_bool &done, std::int32_t id) {
  std::size_t prev_size = 0;

  while (true) {
    std::this_thread::sleep_for(std::chrono::milliseconds(200));
    auto last = news_vector.back();

    if (!last.has_value()) {
      std::print("Reader {}: no news yet\n", id);
      continue;
    }

    std::size_t current_size = news_vector.size();
    if (current_size == prev_size && !done)
      continue;
    if (current_size == prev_size && done)
      break;

    std::print("Reader {}: reads '{}'\n", id, *last);
    prev_size = current_size;
  }

  std::print("Reader {}: finished.\n", id);
}
} // namespace workers
