#pragma once

#include "ESIOTypes.h"
#include "Http.h"
#include "Delegates/Delegate.h"
#include "Runtime/Core/Public/Containers/Map.h"
#include "LatentActions.h"
#include "Engine/LatentActionManager.h"
#include "ESJsonObject.h"
#include "ESRequestJSON.generated.h"

class UESJsonObject;
/**
 * @author Original latent action class by https://github.com/unktomi
 */
template <class T> class EMOSHAPESUBSYSTEM_API FEmoShapeJsonLatentAction : public FPendingLatentAction
{
public:
	virtual void Call(const T &Value) 
	{
		Result = Value;
		Called = true;
	}

	void operator()(const T &Value)
	{
		Call(Value);
	}

	void Cancel();
  
	FEmoShapeJsonLatentAction(FWeakObjectPtr RequestObj, T& ResultParam, const FLatentActionInfo& LatentInfo) :
		Called(false),
		Request(RequestObj),
		ExecutionFunction(LatentInfo.ExecutionFunction),
		OutputLink(LatentInfo.Linkage),
		CallbackTarget(LatentInfo.CallbackTarget),
		Result(ResultParam)
	{
	}
  
	virtual void UpdateOperation(FLatentResponse& Response) override
	{
		Response.FinishAndTriggerIf(Called, ExecutionFunction, OutputLink, CallbackTarget);
	}

	virtual void NotifyObjectDestroyed()
	{
		Cancel();
	}

	virtual void NotifyActionAborted()
	{
		Cancel();
	}

private:
	bool Called;
	FWeakObjectPtr Request;

public:
	const FName ExecutionFunction;
	const int32 OutputLink;
	const FWeakObjectPtr CallbackTarget;
	T &Result;
};


/** Generate a delegates for callback events */
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnRequestComplete, class UESRequestJSON*, Request);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnRequestFail, class UESRequestJSON*, Request);

DECLARE_MULTICAST_DELEGATE_OneParam(FOnStaticRequestComplete, class UESRequestJSON*);
DECLARE_MULTICAST_DELEGATE_OneParam(FOnStaticRequestFail, class UESRequestJSON*);

UCLASS(BlueprintType, Blueprintable)
class EMOSHAPESUBSYSTEM_API UESRequestJSON : public UObject
{
	GENERATED_UCLASS_BODY()
	
public:
	//////////////////////////////////////////////////////////////////////////
	// Construction

	/** Creates new request (totally empty) */
	UFUNCTION(BlueprintCallable, meta = (DisplayName = "Construct Json Request (Empty)", HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject"), Category = "EmoShapeJson|Request")
	static UESRequestJSON* ConstructRequest(UObject* WorldContextObject);

	/** Creates new request with defined verb and content type */
	UFUNCTION(BlueprintCallable, meta = (DisplayName = "Construct Json Request", HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject"), Category = "EmoShapeJson|Request")
	static UESRequestJSON* ConstructRequestExt(UObject* WorldContextObject, EEmoShapeIORequestVerb Verb, EEmoShapeIORequestContentType ContentType);

	/** Set verb to the request */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request")
	void SetVerb(EEmoShapeIORequestVerb Verb);

	/** Set custom verb to the request */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request")
	void SetCustomVerb(FString Verb);

	/** Set content type to the request. If you're using the x-www-form-urlencoded, 
	 * params/constaints should be defined as key=ValueString pairs from Json data */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request")
	void SetContentType(EEmoShapeIORequestContentType ContentType);

	/** Set content type of the request for binary post data */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request")
	void SetBinaryContentType(const FString &ContentType);

	/** Set content of the request for binary post data */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request")
	void SetBinaryRequestContent(const TArray<uint8> &Content);

	/** Sets optional header info */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request")
	void SetHeader(const FString& HeaderName, const FString& HeaderValue);


	//////////////////////////////////////////////////////////////////////////
	// Destruction and reset

	/** Reset all internal saved data */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Utility")
	void ResetData();

	/** Reset saved request data */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request")
	void ResetRequestData();

	/** Reset saved response data */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Response")
	void ResetResponseData();

	/** Cancel latent response waiting  */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Response")
	void Cancel();


	//////////////////////////////////////////////////////////////////////////
	// JSON data accessors

	/** Get the Request Json object */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request")
	UESJsonObject* GetRequestObject();

	/** Set the Request Json object */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request")
	void SetRequestObject(UESJsonObject* JsonObject);

	/** Get the Response Json object */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Response")
	UESJsonObject* GetResponseObject();

	/** Set the Response Json object */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Response")
	void SetResponseObject(UESJsonObject* JsonObject);


	///////////////////////////////////////////////////////////////////////////
	// Request/response data access

	/** Get url of http request */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request")
	FString GetURL();

	/** Get status of http request */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request")
	EEmoShapeIORequestStatus GetStatus();

	/** Get the response code of the last query */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Response")
	int32 GetResponseCode();

	/** Get value of desired response header */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Response")
	FString GetResponseHeader(const FString HeaderName);
	
	/** Get list of all response headers */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Response")
	TArray<FString> GetAllResponseHeaders();

	//////////////////////////////////////////////////////////////////////////
	// URL processing

	/** Open URL with current setup */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request")
	virtual void ProcessURL(const FString& Url = TEXT("http://alyamkin.com"));

	/** Open URL in latent mode */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Request", meta = (Latent, LatentInfo = "LatentInfo", HidePin = "WorldContextObject", DefaultToSelf = "WorldContextObject"))
	virtual void ApplyURL(const FString& Url, UESJsonObject *&Result, UObject* WorldContextObject, struct FLatentActionInfo LatentInfo);

	/** Apply current internal setup to request and process it */
	void ProcessRequest();


	//////////////////////////////////////////////////////////////////////////
	// Request callbacks

private:
	/** Internal bind function for the IHTTPRequest::OnProcessRequestCompleted() event */
	void OnProcessRequestComplete(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);

	void OnProcessRequestCompleteBinaryResult(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);

public:
	/** Event occured when the request has been completed */
	UPROPERTY(BlueprintAssignable, Category = "EmoShapeJson|Event")
	FOnRequestComplete OnRequestComplete;

	/** Event occured when the request wasn't successfull */
	UPROPERTY(BlueprintAssignable, Category = "EmoShapeJson|Event")
	FOnRequestFail OnRequestFail;
	
	/** Event occured when the request has been completed */
	FOnStaticRequestComplete OnStaticRequestComplete;
	
	/** Event occured when the request wasn't successfull */
	FOnStaticRequestFail OnStaticRequestFail;
	

	//////////////////////////////////////////////////////////////////////////
	// Tags

public:
	/** Add tag to this request */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Utility")
	void AddTag(FName Tag);

	/** 
	 * Remove tag from this request 
	 *
	 * @return Number of removed elements 
	 */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Utility")
	int32 RemoveTag(FName Tag);

	/** See if this request contains the supplied tag */
	UFUNCTION(BlueprintCallable, Category = "EmoShapeJson|Utility")
	bool HasTag(FName Tag) const;

protected:
	/** Array of tags that can be used for grouping and categorizing */
	TArray<FName> Tags;


	//////////////////////////////////////////////////////////////////////////
	// Data

public:
	/** Request response stored as a string */
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "EmoShapeJson|Response")
	FString ResponseContent;

	/** Is the response valid JSON? */
	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "EmoShapeJson|Response")
	bool bIsValidJsonResponse;

	/** If this is true it will call back on the binary callback instead of json */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "EmoShapeJson|Response")
	bool bShouldHaveBinaryResponse;

	TFunction<void(TArray<uint8>&)> OnProcessURLCompleteCallback;

	TArray<uint8> ResultBinaryData;

protected:
	/** Latent action helper */
	FEmoShapeJsonLatentAction<UESJsonObject*>* ContinueAction;

	/** Internal request data stored as JSON */
	UPROPERTY()
	UESJsonObject* RequestJsonObj;

	UPROPERTY()
	TArray<uint8> RequestBytes;

	UPROPERTY()
	FString BinaryContentType;

	/** Response data stored as JSON */
	UPROPERTY()
	UESJsonObject* ResponseJsonObj;

	/** Verb for making request (GET,POST,etc) */
	EEmoShapeIORequestVerb RequestVerb;

	/** Content type to be applied for request */
	EEmoShapeIORequestContentType RequestContentType;

	/** Mapping of header section to values. Used to generate final header string for request */
	TMap<FString, FString> RequestHeaders;

	/** Cached key/value header pairs. Parsed once request completes */
	TMap<FString, FString> ResponseHeaders;

	/** Http Response code */
	int32 ResponseCode;

	/** Custom verb that will be used with RequestContentType == CUSTOM */
	FString CustomVerb;

	/** Request we're currently processing */
	FHttpRequestRef HttpRequest = FHttpModule::Get().CreateRequest();
	
};
