#include "InitManager.h"
#include "client/v3beta/dto/product/product_dto.pb.h"
#include "client/v3beta/dto/shared/api.pb.h"
#include "Tools/CsdkCommonHttp.h"
#include "Tools/CsdkCommonTools.h"

using namespace heroim::client::v3beta::dto::product;

void FInitManager::Init(const FString& ProductId,const FString& ProductKey,const FString& Url,
	const TFunction<void(const int32 ErrorCode, const FString&)>& CallBack)
{
#if CSDK_WITH_CHECK
	checkf(!bIsInit,TEXT("Can't init twice"))
#endif
	
	SystemSetting.SetInitData(ProductId,ProductKey,Url);
	CSDK_LOG(LogChatSdk,Log,TEXT("ProductId：%s,ProductKey:%s,Url:%s"),*ProductId,*ProductKey,*Url);

	ProductConfigRequest ConfigRequest;
	ConfigRequest.set_allocated_base( FCsdkCommonTools::MakePbBase());

	auto HttpCallBack =[this,CallBack](const int32 ErrorCode,const FString& ErrorMsg,const ProductConfigResponse& Resp)
	{
		if(ErrorCode == ECsdkErrorCode::Success)
		{
			bIsInit = true;
			const FString WsAddress =STD_STRING_TO_FSTRING(Resp.node().wsaddress());
			SystemSetting.SetWsAddress(WsAddress);
			CSDK_LOG(LogChatSdk,Log,TEXT("WsAdress Is %s"),*WsAddress)
		}
		CallBack(ErrorCode,ErrorMsg);
	};
	FCsdkCommonHttp<ProductConfigResponse>::Request(TEXT("/spi/v3beta/pub/config"),ConfigRequest,HttpCallBack);
}

void FInitManager::DeInit()
{
	bIsInit = false;
	SystemSetting.ClearInitData();
}

void FInitManager::Reset()
{
	bIsInit = false;
}
