#include "datetime.h"
#include <chrono>
#include <ctime>
#include <iomanip>
#include <sstream>

using namespace std::chrono;

namespace myapp::utils {

namespace {

std::tm to_local_time(std::time_t t)
{
    std::tm buf;
    ::localtime_r(&t, &buf);

    return buf;
}

std::tm to_universal_time(std::time_t t)
{
    std::tm buf;
    ::gmtime_r(&t, &buf);

    return buf;
}

std::string fmt_time(struct tm& time, const char* fmt)
{
    std::stringstream ss;
    ss << std::put_time(&time, fmt);
    return ss.str();
}
    
} /* namespace myapp::utils::{anonymous} */

datetime::datetime(std::time_t t) noexcept
  : t_(t)
{
}

datetime datetime::now() noexcept
{
    auto now = system_clock::now();
    auto now_c = system_clock::to_time_t(now);
    return datetime(now_c);
}

std::string datetime::local_time() const
{
    auto time = to_local_time(t_);
    return fmt_time(time, "%F %T");
}

std::string datetime::universal_time() const
{
    auto time = to_universal_time(t_);
    return fmt_time(time, "%F %T");
}

std::string datetime::long_time() const
{
    auto time = to_local_time(t_);
    return fmt_time(time, "%T");
}

std::string datetime::short_time() const
{
    auto time = to_local_time(t_);
    return fmt_time(time, "%R");
}

} /* namespace myapp::utils */
