// (CVN) - Candy Valley Network GmbH

#include "Adapters/LovenseConnectDesktopAdapter.h"

// EXTERNAL INCLUDES
#include <HttpModule.h>
#include <IHttpRequest.h>

// INTERNAL INCLUDES
#include "LovenseToy.h"
#include "LovenseWebThread.h"


LovenseConnectDesktopAdapter::LovenseConnectDesktopAdapter()
	: LovenseConnectAdapterBase() {}

void LovenseConnectDesktopAdapter::GetToys(FOnLovenseGetToysResponse callback) {
#if WITH_LOVENSE
	TMap<FString, FString> headers;
	//headers.Add(TEXT("Content-Type"), TEXT("application/json"));
	FString url = FString::Printf(TEXT("%s://%s:%d/GetToys"), *this->webProtocol, *this->deviceIp,this->webProtocol.Equals(TEXT("https")) ? this->adapterDescription.httpsPort : this->adapterDescription.httpsPort);
	RequestToys(url, true, TEXT("GET"), TEXT(""), headers, callback);

#endif
}

void LovenseConnectDesktopAdapter::WebThread_SendCommand(const FString& command, FOnLovenseResponse callback) {
//	FHttpRequestPtr httpRequest = FHttpModule::Get().CreateRequest();
//#if WITH_LOVENSE
//	httpRequest->SetVerb(TEXT("POST"));
//	httpRequest->SetHeader("Content-Type", "application/json");
//	//TArray<uint8> RawData;
//	//FTCHARToUTF8 Converter(command);
//	//RawData.Append(reinterpret_cast<const uint8*>(Converter.Get()), Converter.Length());
//
//	httpRequest->SetURL(FString::Printf(TEXT("%s://%s:%d/command"), *this->webProtocol, *this->deviceIp, this->adapterDescription.httpsPort));
//	// 将字节数据分配给 RawBodyData
//	httpRequest->SetContentAsString(command);
//#endif
//	return httpRequest;
#if WITH_LOVENSE
	FString url = TEXT("");
	url = FString::Printf(TEXT("%s://%s:%d/command"), *this->webProtocol, *this->deviceIp, this->webProtocol.Equals(TEXT("https")) ? this->adapterDescription.httpsPort : this->adapterDescription.httpPort);
	TMap<FString, FString> headers;
	headers.Add(TEXT("Content-Type"), TEXT("application/json"));
	LovenseWebThread* webThread = new LovenseWebThread(url, true, TEXT("POST"), *command, headers, TEXT("thread_sendCommand"), callback, [&](const FString response, FOnLovenseResponse callback) {
		// Parse response into a json object.
		TSharedPtr<FJsonObject> jsonObject = MakeShareable(new FJsonObject());
		TSharedRef<TJsonReader<TCHAR>> jsonReader = TJsonReaderFactory<TCHAR>::Create(response);
		FJsonSerializer::Deserialize(jsonReader, jsonObject);

		// Retrieve response status.
		TSharedPtr<FJsonValue> codeValue = jsonObject->GetField<EJson::None>(TEXT("code"));
		// If there is no "code" field or the code is not 200 (which means success), execute callback with -1 to indicate that we couldn't determine the battery status.
		if (codeValue->IsNull()) return (void)callback.ExecuteIfBound(-1);
		int32 code = FMath::RoundHalfFromZero(codeValue->AsNumber());
		return (void)callback.ExecuteIfBound(code);

		});
	FRunnableThread* myThread = FRunnableThread::Create(webThread, TEXT("MyRunnableThread"));
#endif
}
