#include <gtest/gtest.h>

#include <buildboxcommon_fileutils.h>
#include <buildboxcommon_logging.h>
#include <buildboxworker_config.h>

using namespace buildboxworker;

using namespace testing;

TEST(ConfigReader, UnhealthyFromFile)
{
    const auto filename = "unhealthy.conf";
    ASSERT_TRUE(buildboxcommon::FileUtils::isRegularFile(filename));

    const std::string configFileName(filename);
    const proto::BotStatus status =
        Config::getStatusFromConfigFile(configFileName);

    EXPECT_EQ(status, proto::BotStatus::UNHEALTHY);
}

TEST(ConfigReader, UnhealthyFrom2)
{
    std::stringstream ss;
    ss << "botStatus: " << proto::BotStatus::HOST_REBOOTING;
    const proto::BotStatus status = Config::getStatusFromConfigStream(&ss);

    EXPECT_EQ(status, proto::BotStatus::HOST_REBOOTING);
}

TEST(ConfigReader, InvalidStatus)
{
    std::stringstream ss;
    ss << "botStatus: -42";
    const proto::BotStatus status = Config::getStatusFromConfigStream(&ss);

    // If we read an invalid status then return healthy by default.
    EXPECT_EQ(status, proto::BotStatus::OK);
}

TEST(ConfigReader, FileDoesntExist)
{
    const auto filename = "/some/file";
    ASSERT_FALSE(buildboxcommon::FileUtils::isRegularFile(filename));

    const proto::BotStatus status =
        Config::getStatusFromConfigFile("/some/file");
    // If we can't open the file then mark ourselves ok.
    EXPECT_EQ(status, proto::BotStatus::OK);
}

TEST(ConfigReader, NoFile)
{
    const proto::BotStatus status = Config::getStatusFromConfigFile("");
    // If we can't open the file then mark ourselves ok.
    EXPECT_EQ(status, proto::BotStatus::OK);
}

TEST(ConfigReader, ExtraContent)
{
    std::stringstream ss;
    ss << "botStatus: 4\n";
    ss << "somethingElse: 12\n";
    const proto::BotStatus status = Config::getStatusFromConfigStream(&ss);

    // Invalid configs are rejected
    EXPECT_EQ(status, proto::BotStatus::OK);
}
