#include "files_queue.h"
#include <boost/filesystem.hpp>
#include <maps/libs/common/include/exception.h>
#include <fstream>

namespace maps::wiki::json2ymapsdf {

namespace bf = boost::filesystem;

namespace {
const std::string JSON_EXTENSION = ".json";

void
pushFile(ThreadedQueue<std::string>& queue, const std::string& fileName)
{
    queue.push(fileName);
    INFO() << "File: " << fileName << " queued";
}
} // namespace

void
initFilesQueue(ThreadedQueue<std::string>& queue, const Params& params)
{
    // --json-file
    if (!params.jsonFile.empty()) {
        pushFile(queue, params.jsonFile);
        queue.finish();
        return;
    }

    // --json-list
    if (!params.jsonList.empty()) {
        std::ifstream filesList(params.jsonList);
        std::string fileName;
        while(std::getline(filesList, fileName)) {
            pushFile(queue, fileName);
        }
        queue.finish();
        return;
    }

    // --json-dir
    bf::path path(params.jsonDir);
    REQUIRE(bf::is_directory(path), "Source directory <" << path << "> doesn't exist");

    bf::directory_iterator end;
    for (bf::directory_iterator it(path); it != end; ++it) {
        if (bf::is_regular_file(it->status()) && bf::extension(it->path()) == JSON_EXTENSION)
        {
            pushFile(queue, it->path().string());
        }
    }
    queue.finish();
}

} // namespace maps::wiki::json2ymapsdf
