#include "Manager/CsdkManager.h"

#include "HAL/PlatformFileManager.h"
#include "Misc/FileHelper.h"
#include "Tools/CsdkCommonHttp.h"

FCsdkManager& FCsdkManager::GetInstance()
{
	static FCsdkManager Inst;
	return Inst;
}

void FCsdkManager::Register(UCsdkSubsystem* InSubsystem)
{
	Subsystem = InSubsystem;
	bIsAlive = true;
	FCoreDelegates::OnPreExit.AddLambda([this]()
	{
		this->bIsAlive = false;
		CSDK_LOG(LogChatSdk,Log,TEXT("Project is Exit"));
		GetCommonHttpBaseMap().Empty();
	});
}

void FCsdkManager::Unregister()
{
	Subsystem = nullptr;
	
	InitManager.Reset();
	LoginManager.Reset();
	FriendManager.Reset();
	BlockManager.Reset();
	UserManager.Reset();
	MessageManager.Reset();
	SessionManager.Reset();
	ChatRoomManager.Reset();
	bIsAlive = false;
}

FString FCsdkManager::GetDeviceId()
{
	if(!DeviceId.IsEmpty())
		return DeviceId;
	
	const FString CsdkDeviceIdPath =FPaths::Combine(FPaths::ProjectSavedDir(),TEXT("Csdk"), TEXT("DeviceId"));
	if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*CsdkDeviceIdPath))
	{
		DeviceId = FGuid::NewGuid().ToString();
		FFileHelper::SaveStringToFile(DeviceId, *CsdkDeviceIdPath);
	}
	else
	{
		FFileHelper::LoadFileToString(DeviceId, *CsdkDeviceIdPath);
	}
	return DeviceId;
}


