#include  "AuthState.h"
#include "Log/CsdkLogMacros.h"
#include "Manager/CsdkManager.h"
#include "Tools/Parser/ApiResult.h"
#include "Tools/Parser/TransData.h"
#include "Log/LogChatSdk.h"
#include "../WebSocketConnection.h"
#include "socket/socket_dto.pb.h"
#include "Tools/CsdkCommonTools.h"
#include "Common/CsdkErrorCode.h"

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

void FAuthState::Enter()
{
	
	AuthRequest AuthRequest;
	AuthRequest.set_productid(FSTRING_TO_STD_STRING( FCsdkCommonTools::GetProductId()));
	AuthRequest.set_serverid(FSTRING_TO_STD_STRING( FCsdkCommonTools::GetUserManager().GetCurrentUserId().ServerId));
	AuthRequest.set_token(TCHAR_TO_UTF8(*Manager.Token));

	const FTransData Data{ServerEOpCode::OpAuth,FCsdkCommonTools::ConvertPbStructToBytes(AuthRequest) };
	WebSocketConnection->SendBinaryMessage(Data.Serialize());
	CSDK_LOG(LogChatSdk,Log,TEXT("Enter AuthState with SystemSetting: %s, Token:%s"),
		*FCsdkCommonTools::GetSystemSetting().ToString(),
		*Manager.Token);
}

void FAuthState::OnWebSocketNotify(const TArray<uint8>& Data)
{
	const TApiResult<AuthResponse> Response = TApiResult<AuthResponse>::ParseAPIResult(Data);
	if(Response.Code ==ECsdkErrorCode::Success)
	{
		if(!Manager.bHasLogin) //还未登录成功
		{
			Manager.bHasLogin = true;
		}
		CSDK_LOG(LogChatSdk,Log,TEXT("AuthState Reply success"));
		SwitchState(ELoginStateId::Online);
	}
	CallLoginCallback(Response.Code,Response.Msg);
	//@todo, 超过三天，授权失效
	/*else//授权失败
	{
		if(!Manager->bHasLogin)//登录中直接报错
		{
			CSDK_LOG(LogChatSdk,Log,TEXT("AuthState Reply Failed with Msg:%s"),*Response.Msg);
			CallLoginCallback(false,Response.Msg);
		}
		else if(Manager->LoginWay ==ELoginWay::TokenLogin)
		{
			SwitchState(ELoginStateId::TokenLogin);
		}
		else if(Manager->LoginWay ==ELoginWay::UserLogin)
		{
			SwitchState(ELoginStateId::UserLogin);
		}
		else
		{
			checkf(true,TEXT("Auth Error! Unkown Way to here"));
		}
	}*/
}
