// Fill out your copyright notice in the Description page of Project Settings.


#include "WebSocketManager.h"

#include "Definations.h"
#include "JsonObjectConverter.h"
#include "WebSocketHandler.h"

void UWebSocketManager::InitWebSocket(const FString& ServerIP)
{
	WebSocketHandler = UWebSocketHandler::CreateWebSocket(GEditor->GetEditorWorldContext().World());
	WebSocketHandler->OnConnected.AddDynamic(this, &UWebSocketManager::HandleConnected);
	WebSocketHandler->OnClosed.AddDynamic(this, &UWebSocketManager::HandleClosed);
	WebSocketHandler->OnConnectionError.AddDynamic(this, &UWebSocketManager::HandleConnectionError);
	WebSocketHandler->OnMessageSent.AddDynamic(this, &UWebSocketManager::HandleOnMessageSend);
	WebSocketHandler->OnTextMessage.AddDynamic(this, &UWebSocketManager::HandleOnReceiveText);
	WebSocketHandler->Open(FWebSocketOptions(EWebSocketProtocol::WS, FString::Printf(TEXT("ws://%s:8000/ws/%s")
		,*ServerIP, *(FGuid::NewGuid().ToString()) )));
}

void UWebSocketManager::SendData(const FString& Data)
{
	
	WebSocketHandler->SendText(Data);
}

void UWebSocketManager::HandleConnected()
{
	UE_LOG(LogTemp, Warning, TEXT("WebSocket Server Connect Success"));
	OnConnectDelegate.Broadcast(true);
}


void UWebSocketManager::HandleClosed(const int32& Code, const FString& Reason, bool bClosedByPeer)
{
	UE_LOG(LogTemp, Warning, TEXT("WebSocket Server Closed, code = %d reason = %s"), Code, *Reason);
	OnConnectDelegate.Broadcast(false);
}

void UWebSocketManager::HandleConnectionError(const FString& ErrorReason)
{
	UE_LOG(LogTemp, Warning, TEXT("WebSocket Server connect error, reason = %s"),  *ErrorReason);
	OnConnectDelegate.Broadcast(false);
}

void UWebSocketManager::HandleOnMessageSend(const FString& Message)
{
	UE_LOG(LogTemp, Warning, TEXT("Send Text %s to WebSocket Server "), *Message);
}

void UWebSocketManager::HandleOnReceiveText(const FString& Message)
{
	
		FAIServerData ServerData;
	FJsonObjectConverter::JsonObjectStringToUStruct<FAIServerData>(
		Message, 
		&ServerData, 
		0,  // 检查标志位
		0   // 转换标志位
	);
	switch (ServerData.statusCode)
	{
	case -1:
		UE_LOG(LogTemp, Error, TEXT("ai server error reason = %s "), *ServerData.messages[0]);
		OnDataReceiveDelaget.Broadcast(TArray<FString>());
		break;
	case 0:
		//normal heart tick 
		break;
	case 1:
		UE_LOG(LogTemp, Warning, TEXT("Receive Text %s from WebSocket Server "), *Message);
		OnDataReceiveDelaget.Broadcast(ServerData.messages);
		break;
	default:
			break;
	}
}
