#include <gtest/gtest.h>

#include "log.h"

#if 1
TEST(LOG, STDERR)
{
    char buffer[1024] = {0};
    const char *config = "./conf/log_stderr.toml";
    snprintf(buffer, sizeof(buffer), "sed -i 's/DEBUG/ERROR/g' %s", config);
    EXPECT_TRUE(log_init(config) == 0);

    LOG_TRACE("test", "test log 1");
    LOG_DEBUG("test", "test log 1");
    LOG_INFO("test", "test log 1");
    LOG_WARN("test", "test log 1");
    LOG_ERROR("test", "test log 1");
    LOG_FATAL("test", "test log 1");
    LOG_STATE("test", "test log 1");

    system(buffer);
    log_reload_level(config);

    LOG_TRACE("test", "test log 2");
    LOG_DEBUG("test", "test log 2");
    LOG_INFO("test", "test log 2");
    LOG_WARN("test", "test log 2");
    LOG_ERROR("test", "test log 2");
    LOG_FATAL("test", "test log 2");
    LOG_STATE("test", "test log 2");

    log_free();
}
#endif

#if 1
TEST(LOG, FILE)
{
    char buffer[1024] = {0};
    const char *config = "./conf/log_file.toml";
    snprintf(buffer, sizeof(buffer), "sed -i 's/DEBUG/ERROR/g' %s", config);
    EXPECT_TRUE(log_init(config) == 0);

    LOG_TRACE("test", "test log 1");
    LOG_DEBUG("test", "test log 1");
    LOG_INFO("test", "test log 1");
    LOG_WARN("test", "test log 1");
    LOG_ERROR("test", "test log 1");
    LOG_FATAL("test", "test log 1");
    LOG_STATE("test", "test log 1");

    system(buffer);
    log_reload_level(config);

    LOG_TRACE("test", "test log 2");
    LOG_DEBUG("test", "test log 2");
    LOG_INFO("test", "test log 2");
    LOG_WARN("test", "test log 2");
    LOG_ERROR("test", "test log 2");
    LOG_FATAL("test", "test log 2");
    LOG_STATE("test", "test log 2");

    log_free();
}
#endif

#if 1
TEST(LOG, REOPEN)
{
    char buffer1[1024] = "date \"+%Y-%m-%d\" >> .date.txt";
    char buffer2[1024] = "date -s 2099/01/01";
    char buffer3[1024] = "cat .date.txt | xargs date -s && rm .date.txt";
    const char *config = "./conf/log_file.toml";

    system(buffer1); // record current date

    EXPECT_TRUE(log_init(config) == 0);

    for (int i = 0; i < 3; i++)
    {
        LOG_TRACE("test", "test log %d", i);
        LOG_DEBUG("test", "test log %d", i);
        LOG_INFO("test", "test log %d", i);
        LOG_WARN("test", "test log %d", i);
        LOG_ERROR("test", "test log %d", i);
        LOG_FATAL("test", "test log %d", i);
        LOG_STATE("test", "test log %d", i);
        if (i == 1)
        {
            system(buffer2); // set date to 2099/01/01
        }
        else if (i == 2)
        {
            system(buffer3); // recover date
        }
    }

    log_free();
}
#endif

int main(int argc, char **argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}
