#include <csignal>
#include <iostream>

#include "../include/FileUtils.h"
#include "../include/ServerUtils.h"
#include "../include/ConcurrentQueue.h"
#include "../include/TrackerUtils.h"
#include "../include/Track.h"
#include "../include/MetricsExporter.h"
#include "../include/Options.h"

using namespace std;

int main(const int argc, const char* argv[]) {
    Options options;

    if (argc > 5) {
        cout << "Too many arguments";
        return 0;
    }

    if (!FileUtils::fileExists(argv[1])) {
        cout << "Filepath: " << argv[1] << " doesn't exist.";
        return 0;
    }
    options.word_lists = argv[1];

    if (!FileUtils::fileExists(argv[2])) {
        cout << "Filepath: " << argv[2] << " doesn't exist.";
        return 0;
    }
    options.css = argv[2];

    if (!FileUtils::fileExists(argv[3])) {
        cout << "Filepath: " << argv[3] << " doesn't exist.";
        return 0;
    }
    options.images = argv[3];

    if (!FileUtils::fileExists(argv[4])) {
        cout << "Filepath: " << argv[4] << " doesn't exist.";
        return 0;
    }
    options.favicon = argv[4];

    //cout << options.word_lists << " " << options.css << " " << options.images << " " << endl;

    auto queue = make_shared<ConcurrentQueue<Track>>();
    auto metrics = make_shared<unordered_map<uint32_t, Crawler>>();

    thread(TrackerUtils::track, queue, metrics).detach();

    thread(MetricsExporter::serve, metrics).detach();

    signal(SIGPIPE, SIG_IGN);
    ServerUtils::serve(queue, options);

    return 0;
}