#pragma once

#include "Common/CsdkErrorCode.h"
#include "Interfaces/IHttpRequest.h"
#include "message/message_dto.pb.h"
#include "Message/Core/CsdkMessageBase.h"
#include "Message/Core/CsdkMessageRingBuffer.h"
#include "Message/Data/CsdkMsgPullDirection.h"

//auto Delete
class FPullMsgAutoDeleteTask : public FGCObject
{
public:
	FPullMsgAutoDeleteTask(const FCsdkSessionId& InSessionId, const FString& InAnchorMsgId, const int32 InDesiredPullCount, const ECsdkMsgPullDirection InDirection,
		 const TFunction<void(const int32 ErrorCode, const FString& ErrorMsg,const TArray<UCsdkMessageBase*>& Msgs)>& InCallback,
		 const TWeakPtr<FCsdkMessageRingBuffer>& InWeakMessageRingBuffer);

	virtual void AddReferencedObjects( FReferenceCollector& Collector ) override;
#if ENGINE_MAJOR_VERSION>=5 && ENGINE_MINOR_VERSION>=3
	virtual FString GetReferencerName() const override
	{
		return TEXT("FPullMsgAutoDeleteTask");
	}
#endif
	void StartTask();
private:
	heroim::client::v3beta::dto::message::MessageHistoryRequest MakeRequest(const FString& InAnchorMsgId);
	void StartHttpRequest(const heroim::client::v3beta::dto::message::MessageHistoryRequest& Request);
	void OnHttpResponse(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bConnectedSuccessfully);
	void FillData(const ::herogoogle::protobuf::RepeatedPtrField< ::heroim::client::v3beta::dto::message::model::Message >& List);
	void TryAddToRingBuffer(const TArray<UCsdkMessageBase*>& Msgs,const bool bIsFullCount) const;
	void Completed(const FString& ErrorMsg,const bool bIsFullCount = true) ;
	void AsyncErrorQuit(const ECsdkErrorCode::Type& ErrorCode,const FString& ErrorMsg) const;
	void ErrorQuit(const int32 ErrorCode,const FString& ErrorMsg) const;
	TArray<TObjectPtr<UCsdkMessageBase>> AssembleResult() const;
private:
	FCsdkSessionId SessionId;
	TWeakPtr<FCsdkMessageRingBuffer> WeakMessageRingBuffer =nullptr;
	FString AnchorMsgId;
	int32 DesiredPullCount =0;
	ECsdkMsgPullDirection Direction =ECsdkMsgPullDirection::Forward;
	TArray<TObjectPtr<UCsdkMessageBase>> LocalCachedMessages;
	TArray<TObjectPtr<UCsdkMessageBase>> PulledAllMessages;
	TArray<TObjectPtr<UCsdkMessageBase>> PulledFilteredMessages;
	TFunction<void(const int32, const FString& ,const TArray<UCsdkMessageBase*>&)> Callback = nullptr;
	static const FString Url;
};
