#include "bucket_finder.h"

#include <algorithm>
#include <iterator>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

// class Bucket

void Bucket::insert(const WordList &word_list, size_t first_index,
                    size_t last_index) {
  for (auto index = first_index; index < last_index; ++index) {
    const auto &current_word = word_list[index];
    directory_[current_word.front()].push_back(&current_word);
  }
}

WordRefList Bucket::find_prefix(std::string_view search_term) const {
  auto directory_it = directory_.find(search_term.front());
  if (directory_it == directory_.cend()) {
    return {};
  }

  WordRefList result;
  for (const auto *word : directory_it->second) {
    if (word->starts_with(search_term)) {
      result.push_back(word);
    }
  }

  return result;
}

// class BucketFinder

BucketFinder::BucketFinder(const WordList &word_list) { insert(word_list); }

void BucketFinder::insert(const WordList &word_list) {
  if (word_list.empty()) {
    return;
  }

  const size_t max_threads = std::thread::hardware_concurrency();
  const size_t word_list_size = word_list.size();
  const size_t bucket_count = std::min<size_t>(max_threads, word_list_size);
  const size_t bucket_size = word_list_size / bucket_count;

  buckets_.resize(bucket_count);

  std::vector<std::thread> insert_threads;
  for (auto bucket_index = 0; bucket_index < bucket_count; ++bucket_index) {
    auto &thread_bucket = buckets_[bucket_index];

    const bool is_last_bucket = bucket_index == bucket_count - 1;
    const size_t first_word_index = bucket_index * bucket_size;
    const size_t last_word_index =
        is_last_bucket ? word_list_size : first_word_index + bucket_size;

    insert_threads.emplace_back([&, first_word_index, last_word_index] {
      thread_bucket.insert(word_list, first_word_index, last_word_index);
    });
  }

  for (auto &thread : insert_threads) {
    thread.join();
  }
}

WordRefList BucketFinder::find_prefix(std::string_view search_term) const {
  WordRefList search_results;
  std::mutex search_results_mutex;

  std::vector<std::thread> search_threads;
  for (const auto &bucket : buckets_) {
    search_threads.emplace_back([&] {
      auto thread_search_results = bucket.find_prefix(search_term);
      if (!thread_search_results.empty()) {
        const std::lock_guard result_lock(search_results_mutex);
        std::move(thread_search_results.begin(), thread_search_results.end(),
                  std::back_inserter(search_results));
      }
    });
  }

  for (auto &thread : search_threads) {
    thread.join();
  }

  return search_results;
};
