#include <maps/wikimap/mapspro/libs/controller/include/profile.h>

namespace maps::wiki::controller {
namespace {

template <class T>
std::string
outputOptional(const std::string& prefix, const T& value)
{
    if (!value) {
        return {};
    }
    std::ostringstream s;
    s << prefix << value;
    return s.str();
}

} // namespace

Profile::Profile(const std::string& where)
    : level_(maps::log8::Level::ERROR)
    , where_(where)
    , asyncTaskID_(0)
{
}

Profile::~Profile()
{
    logState();
}

void
Profile::logState()
{
    std::stringstream messageStream;
    if(message_.length()){
        messageStream << " message: " << message_;
    }
    if(callDetails_.length()){
        messageStream << "  arguments=" << callDetails_;
    }
    switch(level_){
        case maps::log8::Level::INFO:
            INFO() << "duration: " << elapsedTime()
                << "  method: " << where_ << messageStream.str()
                << outputOptional(" task_id: ", asyncTaskID_);
            break;
        case maps::log8::Level::WARNING:
            WARN() << " WARNING: " << "duration: " << elapsedTime()
                << "  method: " << where_ << messageStream.str()
                << outputOptional(" task_id: ", asyncTaskID_);

            break;
        case maps::log8::Level::ERROR:
            ERROR() << "duration: " << elapsedTime()
                << "  method: " << where_ << messageStream.str()
                << outputOptional(" task_id: ", asyncTaskID_);
            break;
        default:
            break;
    };
}

void
Profile::setAsyncTaskID(taskutils::TaskID taskID)
{
    asyncTaskID_ = taskID;
}

std::string
Profile::elapsedTime()
{
    return timer_.getElapsedTime();
}

} // namespace maps::wiki::controller
