#include <yandex/maps/wiki/tasks/ymapsdf.h>

#include <library/cpp/testing/common/env.h>

#include <mutex>

namespace maps::wiki::tasks::ymapsdf {

namespace {

std::mutex mutex;
std::string YMAPSDF_SCHEMAS_DIR = "/usr/share/yandex/maps/ymapsdf2";

const std::string YMAPSDF_GARDEN_SCHEMAS_DIR = "/usr/share/yandex/maps/garden/ymapsdf2";

const std::string ARCADIA_YMAPSDF_PACKAGE_SUBDIR = "/doc/schemas/ymapsdf/package";
const std::string ARCADIA_YMAPSDF_GARDEN_SUBDIR = "/doc/schemas/ymapsdf/garden";
const std::string ARCADIA_YMAPSDF_PACKAGE_DIR = "maps" + ARCADIA_YMAPSDF_PACKAGE_SUBDIR;
const std::string ARCADIA_YMAPSDF_GARDEN_DIR = "maps" + ARCADIA_YMAPSDF_GARDEN_SUBDIR;

} // namespace

const std::string& getArcadiaSchemasDirectory()
{
    return ARCADIA_YMAPSDF_PACKAGE_DIR;
}

std::string getDefaultSchemasDirectory()
{
    std::lock_guard<std::mutex> lock(mutex);
    return YMAPSDF_SCHEMAS_DIR;
}

void setDefaultSchemasDirectory(std::string dir)
{
    std::lock_guard<std::mutex> lock(mutex);
    YMAPSDF_SCHEMAS_DIR = std::move(dir);
}

std::string getArcadiaScriptPath(const std::string& file)
{
    return BinaryPath(getArcadiaSchemasDirectory() + "/" + file);
}

std::string getDefaultScriptPath(const std::string& file)
{
    return getDefaultSchemasDirectory() + "/" + file;
}

std::string getScriptPath(const std::string& file)
{
    return FromYaTest()
        ? getArcadiaScriptPath(file)
        : getDefaultScriptPath(file);
}

std::string getGardenSchemasDirectory()
{
    auto dir = getDefaultSchemasDirectory();

    if (dir.ends_with(ARCADIA_YMAPSDF_PACKAGE_SUBDIR)) {
        auto pos = dir.size() - ARCADIA_YMAPSDF_PACKAGE_SUBDIR.size();
        return dir.substr(0, pos) + ARCADIA_YMAPSDF_GARDEN_SUBDIR;
    }
    return YMAPSDF_GARDEN_SCHEMAS_DIR;
}

} // namespace maps::wiki::tasks::ymapsdf
