#include "ofd.h"
#include "../utils/utils.h"
#include <filesystem>
#include <iostream>
#include <string>
#include <vector>
#include "../net/net.h"
#include "../settings/settings.h"

OFD::OFD() {}

OFD::OFD(std::string path) { this->module = OFDModule(path); };

std::vector<std::string> OFD::search_ofds() {
    Settings s(get_path_relative_to_home(".local/share/checks_parser/settings.json"));
    std::vector<std::string> result{};

    std::string path = get_path_relative_to_home(s.get_setting("ods_modules_dir"));
    std::filesystem::directory_entry modules_dir(path);

    if (!modules_dir.exists()) {
        std::filesystem::create_directories(path);
        std::cout << "No modules directory found. Created one at " << path
                  << std::endl;
        std::cout << "Please, download modules to that directory from my git."
                  << std::endl;
    }

    for (auto file : std::filesystem::directory_iterator(path)) {
        result.push_back(file.path());
    }

    return result;
}

void OFD::set_module(std::string path) { this->module = OFDModule(path); }

std::string OFD::get_check_data(std::string fn, std::string fd,
                                std::string fp) {
    //TODO
    return "";
}

std::vector<std::string> OFD::check_updates() {
    Settings s(get_path_relative_to_home(".local/share/checks_parser/settings.json"));

    std::string path = get_path_relative_to_home(s.get_setting("ofds_modules_dir"));
    std::vector<std::string> to_download;
    std::vector<std::string> stored_modules;

    for (const auto& file : std::filesystem::directory_iterator(path)) {
        if (!file.is_regular_file()) continue;
        stored_modules.push_back(file.path().filename());
        std::cout << "Detected OFD module" << file.path().filename() << std::endl;
    }
    Net n;
    std::vector<std::string> remote_modules = n.get_all_modules(s.get_setting("ofds_modules_url"));

    for (const std::string& module : remote_modules) {
        if (!vector_contains_element(stored_modules, module)) {
            to_download.push_back(module);
            std::cout << "I need to download OFD module " << module << std::endl;
        }
    }

    return to_download;
}
