#include "OfflineState.h"
#include "Log/CsdkLogMacros.h"
#include "Log/LogChatSdk.h"
#include "../WebSocketConnection.h"
#include "Manager/CsdkSubsystem.h"
#include "Tools/CsdkCommonTools.h"


void FReconnectTask::DoWork() const
{
	while (FCsdkCommonTools::IsAlive() && !WebSocketConnection->IsConnected())
	{
		WebSocketConnection->Connect();
		CSDK_LOG(LogChatSdk,Log,TEXT("Async Reconnect"));
		FPlatformProcess::Sleep(1.0f);
	}
}

FOfflineState::~FOfflineState()
{
	Release();
}

void FOfflineState::Enter()
{
	if(MyTask)
	{
		return;
	}
	MyTask = new FAsyncTask<FReconnectTask>( WebSocketConnection );
	MyTask->StartBackgroundTask();
	FCsdkManager::GetInstance().Subsystem->OnDisconnect.Broadcast();
	CSDK_LOG(LogChatSdk,Log,TEXT("Enter OfflineState. Start Reconnect"));
}

void FOfflineState::Leave()
{
	Release();
	CSDK_LOG(LogChatSdk,Log,TEXT("Leave OfflineState. Stop Reconnect"));
}


void FOfflineState::Release()
{
	if(MyTask)
	{
		MyTask->Cancel();
		MyTask = nullptr;
		
	}
}






