#pragma once

#include "tracer.pb.h"
#include "Data/LogItem.h"
#include "HAL/Runnable.h"
#include "HAL/RunnableThread.h"
#include "Containers/Queue.h"

class CSDKRUNTIME_API FLogUploader : public FRunnable
{
public:
	FLogUploader(TArray<FLogItem>& Logs, const FString& DeviceId) : StopTaskCounter(0)
	{
		DeviceUniqueId = DeviceId;
		LogUploaderThread = FRunnableThread::Create(this, TEXT("LogUploaderThread"));
		for (auto& Log : Logs)
		{
			LogQueue.Enqueue(Log);
		}
	}
	
	~FLogUploader() {
		// 设置标志位为true，让线程自动销毁
		Stop();
		if (LogUploaderThread != nullptr) {
			LogUploaderThread->WaitForCompletion();
			delete LogUploaderThread;
			LogUploaderThread = nullptr;
		}
	}
	virtual bool Init() override;
	virtual uint32 Run() override;
	virtual void Stop() override;
	virtual void Exit() override;
	
	bool IsStopRequested() const;
	logtracer::client::v1::LogLevel ConvertVerbosity(const ELogVerbosity::Type Type);
	void UploadLogs(const TArray<FLogItem>& Logs);
	TQueue<FLogItem> LogQueue;
private:
	FString DeviceUniqueId;
	FRunnableThread* LogUploaderThread;
	volatile int32 StopTaskCounter;
};
