#include "../include/ConcurrentQueue.h"
#include "../include/TrackerUtils.h"
#include "../include/WordUtils.h"
#include "../include/Crawler.h"
#include "../include/Track.h"
#include <unordered_map>
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <ranges>
#include <cstdint>

shared_ptr<unordered_map<uint32_t, Crawler>> urls;

void [[noreturn]] TrackerUtils::track(const shared_ptr<ConcurrentQueue<Track>>& s_track, const shared_ptr<unordered_map<uint32_t, Crawler>>& crawler) {
    urls = crawler;

    constexpr bool running = true;

    while (running) {
        Track track;

        if (!s_track->try_pop(track)) {
            this_thread::sleep_for(chrono::milliseconds(100));
            continue;
        }

        (*urls)[track.Ip].links_pressed++;
        (*urls)[track.Ip].user_agent = track.UserAgent;
    }
}

void [[noreturn]] TrackerUtils::print() {
    this_thread::sleep_for(chrono::milliseconds(5000));

    while (true) {
        for (const auto &[user_agent, links_pressed]: *urls | views::values) {
            cerr << links_pressed << ": " << user_agent << endl;
        }

        this_thread::sleep_for(chrono::milliseconds(1000));
        system("clear"); // Testing only
    }
}
