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


#include "PortaHelper.h"

bool FPortaHelper::ParseJsonContent(const FString& Content, TSharedPtr<FJsonObject>& OutJsonObject)
{
	if (Content.IsEmpty())
	{
		return false;
	}

	TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(Content);
	return FJsonSerializer::Deserialize(JsonReader, OutJsonObject);
}


bool FPortaHelper::SerializeJsonToString(const TSharedPtr<FJsonObject>& JsonObject, FString& OutJsonString)
{
	if (!JsonObject.IsValid())
	{
		return false;
	}

	TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&OutJsonString);
	bool bSuccess = FJsonSerializer::Serialize(JsonObject.ToSharedRef(), Writer);
	Writer->Close();
	return bSuccess;
}




bool FPortaHelper::ConvertAndUpdateColorJson(const FString& FieldName, TSharedPtr<FJsonObject>& JsonObject)
{
	const TSharedPtr<FJsonObject>* ColorObject = nullptr;
	if (!JsonObject->TryGetObjectField(FieldName, ColorObject) || !ColorObject)
	{
		return false;
	}

	double R = 0.0, G = 0.0, B = 0.0, A = 0.0;
	if (!(*ColorObject)->TryGetNumberField(TEXT("R"), R) ||
		!(*ColorObject)->TryGetNumberField(TEXT("G"), G) ||
		!(*ColorObject)->TryGetNumberField(TEXT("B"), B) ||
		!(*ColorObject)->TryGetNumberField(TEXT("A"), A))
	{
		return false;
	}

	FColor ByteColor(
		static_cast<uint8>(R),
		static_cast<uint8>(G),
		static_cast<uint8>(B),
		static_cast<uint8>(A)
	);
    
	FLinearColor LinearColor(ByteColor);

	(*ColorObject)->SetNumberField(TEXT("R"), LinearColor.R);
	(*ColorObject)->SetNumberField(TEXT("G"), LinearColor.G);
	(*ColorObject)->SetNumberField(TEXT("B"), LinearColor.B);
	(*ColorObject)->SetNumberField(TEXT("A"), LinearColor.A);

	return true;
}

