#include "VoiceManager.h"
#include "group/chatroom_dto.pb.h"
#include "Log/CsdkLogMacros.h"
#include "Log/LogChatSdk.h"
#include "message/model/operation.pb.h"
#include "Tools/CsdkCommonHttp.h"
#include "Tools/CsdkCommonTools.h"
#include "User/Tool/UserTool.h"

using heroim::client::v3beta::dto::message::model::Command;

void FVoiceManager::ModifyUserMicStatus(const FString& RoomId, const TArray<FCsdkUserMicStatus>& UserStatus,
                                        FModifyUserMicStatusCallback Callback)
{
	using namespace heroim::client::v3beta::dto::group ;
	OpenCloseMicRequest Request;
	Request.set_allocated_base(FCsdkCommonTools::MakePbBase());
	Request.set_gameroomid(TCHAR_TO_UTF8(* RoomId));
	
	for (const auto& Status:UserStatus)
	{
		auto* EntryPtr = new OpenCloseMicRequest_Entry;
		EntryPtr->set_allocated_user(CsdkUserTool::MakePbUserKey(Status.UserId));
		EntryPtr->set_isopen(Status.bIsOpen);
		EntryPtr->set_voiceroleid(TCHAR_TO_UTF8(*Status.OpenId));
		Request.mutable_ops()->AddAllocated(EntryPtr);
	}
	

	auto HttpCallback =[this,Callback](const int32 ErrorCode,const FString& ErrorMsg,const Empty& Resp)
	{
		Callback.ExecuteIfBound(ErrorCode,ErrorMsg);
		CSDK_LOG(LogChatSdk,Log,TEXT("ModifyUserMicStatus response--> ErrorCode:%d,ErrorMsg:%s"),ErrorCode,*ErrorMsg);
	};
	FCsdkCommonHttp<Empty>::Request(TEXT("/spi/v3beta/chatroom/oc-voice-mic"),Request,HttpCallback);
}

void FVoiceManager::OnEventReceived(const EVoiceEventType EventType, const FString& JsonData)
{
	if (EventType == EVoiceEventType::MicEnableMsg)
	{
		TSharedPtr<FJsonObject> RootObject = MakeShareable(new FJsonObject());
		const TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(JsonData);
		bool enableMic = false;
		if (FJsonSerializer::Deserialize(Reader, RootObject))
		{
			
			int32 i = RootObject->GetIntegerField(TEXT("enableMic"));
			if (i == 1)
			{
				enableMic = false;
			}
			else if (i == 2)
			{
				enableMic = true;
			}
		}
		
		auto VoiceSubsystem = FCsdkManager::GetInstance().Subsystem->GetGameInstance()->GetSubsystem<UCsdkVoiceSupportSubsystem>();
		VoiceSubsystem->OnMicStatusChanged.Broadcast(enableMic);
	}
}

