
#include "LogForwarder.h"

#include "LogUploader.h"
#include "Tools/CsdkCommonHttp.h"


DEFINE_LOG_CATEGORY(LogCsdkLogs);

static const float FLUSH_LOGS_INTERVAL = 5.0f;


FLogForwarder::FLogForwarder(const FString& InDeviceId)
{
	flushLogsInSeconds = FLUSH_LOGS_INTERVAL;
	DeviceUniqueId = InDeviceId;
}


FLogForwarder::~FLogForwarder()
{
}


void FLogForwarder::Tick(float DeltaTime)
{
    flushLogsInSeconds -= DeltaTime;
    if (flushLogsInSeconds > 0.0f)
    {
        return;
    }
    
    FlushLogs();
}


TStatId FLogForwarder::GetStatId() const
{
    RETURN_QUICK_DECLARE_CYCLE_STAT(FDriftLogForwarder, STATGROUP_Tickables);
}


void FLogForwarder::FlushLogs()
{
	if (pendingLogs.Num() > 0)
	{
        UE_LOG(LogCsdkLogs, Verbose, TEXT("Flushing %d log entries"), pendingLogs.Num());

		LogUploaderRunnable = MakeShareable(new FLogUploader(pendingLogs, *DeviceUniqueId));
		pendingLogs.Empty();
	}

	flushLogsInSeconds += FLUSH_LOGS_INTERVAL;
}


void FLogForwarder::Log(const FName& Category, ELogVerbosity::Type Verbosity, const FString& Data)
{
	FLogItem LogObject;
	LogObject.Category = Category;
	LogObject.Verbosity = Verbosity;
	LogObject.Data = Data;
    pendingLogs.Emplace(LogObject);
}