/*
 * @license Private Source License v1.0.0
 * @copyright 2023 Reinhardt Weyers
 *
 * @author Reinhardt Weyers
 *
 * @version 0.1.0
 * 
 * Created On: 04/12/25
 * Last edited: 04/12/25
 */

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Linq;
using System.Text;

namespace RetroDev.Networking
{
    /// <summary>
    /// Provides static methods to perform HTTP GET, POST, PUT, and DELETE requests using Unity's UnityWebRequest.
    /// Supports custom headers and error handling callbacks for robust networking operations.
    /// </summary>
    public static class QuickRequest
    {
        /// <summary>
        /// Performs a GET request asynchronously.
        /// </summary>
        /// <param name="url">The URL to send the GET request to.</param>
        /// <param name="headers">Optional headers to include in the request.</param>
        /// <param name="onSuccess">Callback invoked with response text on successful request.</param>
        /// <param name="onError">Callback invoked with error message on request failure.</param>
        public static void Get(string url, Dictionary<string, string> headers, Action<string> onSuccess, Action<string> onError)
        {
            RequestRunner.Instance.StartCoroutine(GetCoroutine(url, headers, onSuccess, onError));
        }

        /// <summary>
        /// Coroutine for handling the GET request.
        /// </summary>
        private static IEnumerator GetCoroutine(string url, Dictionary<string, string> headers, Action<string> onSuccess, Action<string> onError)
        {
            using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
            {
                SetHeaders(webRequest, headers);
                yield return webRequest.SendWebRequest();

                HandleResponse(webRequest, onSuccess, onError);
            }
        }

        /// <summary>
        /// Performs a POST request asynchronously.
        /// </summary>
        /// <param name="url">The URL to send the POST request to.</param>
        /// <param name="formFields">Form data fields for the POST request.</param>
        /// <param name="contentType">The content type the server is expecting.</param>
        /// <param name="headers">Optional headers to include in the request.</param>
        /// <param name="onSuccess">Callback invoked with response text on successful request.</param>
        /// <param name="onError">Callback invoked with error message on request failure.</param>
        public static void Post(string url, Dictionary<string, object> formFields, ContentType contentType, Dictionary<string, string> headers, Action<string> onSuccess, Action<string> onError)
        {
            if (formFields == null)
            {
                onError?.Invoke("Form fields cannot be null");
                return;
            }
            RequestRunner.Instance.StartCoroutine(PostCoroutine(url, formFields, contentType, headers, onSuccess, onError));
        }

        private static IEnumerator PostCoroutine(string url, Dictionary<string, object> formFields, ContentType contentType, Dictionary<string, string> headers, Action<string> onSuccess, Action<string> onError)
        {
            string requestBody = null;
            UnityWebRequest webRequest = null;

            try
            {
                webRequest = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST);
                webRequest.downloadHandler = new DownloadHandlerBuffer();

                switch (contentType)
                {
                    case ContentType.Json:
                        requestBody = Encoder.EncodeContent(formFields, contentType);
                        webRequest.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(requestBody));
                        webRequest.SetRequestHeader("Content-Type", "application/json");
                        break;

                    case ContentType.FormUrlEncoded:
                        requestBody = Encoder.EncodeContent(formFields, contentType);
                        webRequest.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(requestBody));
                        webRequest.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                        break;

                    case ContentType.PlainText:
                        requestBody = Encoder.EncodeContent(formFields, contentType);
                        webRequest.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(requestBody));
                        webRequest.SetRequestHeader("Content-Type", "text/plain");
                        break;

                    default:
                        throw new ArgumentException($"Unsupported ContentType: {contentType}");
                }

                SetHeaders(webRequest, headers);
            }
            catch (Exception ex)
            {
                Debug.LogError($"Error preparing request: {ex.Message}");
                onError?.Invoke($"Request preparation failed: {ex.Message}");
                yield break;
            }

            using (webRequest)
            {
                yield return webRequest.SendWebRequest();

                try
                {
                    HandleResponse(webRequest, onSuccess, onError);
                }
                catch (Exception ex)
                {
                    Debug.LogError($"Error handling response: {ex.Message}");
                    onError?.Invoke($"Response handling failed: {ex.Message}");
                }
            }
        }


        /// <summary>
        /// Performs a PUT request asynchronously.
        /// </summary>
        /// <param name="url">The URL to send the PUT request to.</param>
        /// <param name="jsonData">JSON data for the PUT request.</param>
        /// <param name="headers">Optional headers to include in the request.</param>
        /// <param name="onSuccess">Callback invoked with response text on successful request.</param>
        /// <param name="onError">Callback invoked with error message on request failure.</param>
        public static void Put(string url, string jsonData, Dictionary<string, string> headers, Action<string> onSuccess, Action<string> onError)
        {
            RequestRunner.Instance.StartCoroutine(PutCoroutine(url, jsonData, headers, onSuccess, onError));
        }

        /// <summary>
        /// Coroutine for handling the PUT request.
        /// </summary>
        private static IEnumerator PutCoroutine(string url, string jsonData, Dictionary<string, string> headers, Action<string> onSuccess, Action<string> onError)
        {
            using (UnityWebRequest webRequest = UnityWebRequest.Put(url, jsonData))
            {
                webRequest.SetRequestHeader("Content-Type", "application/json");
                SetHeaders(webRequest, headers);
                yield return webRequest.SendWebRequest();

                HandleResponse(webRequest, onSuccess, onError);
            }
        }

        /// <summary>
        /// Performs a DELETE request asynchronously.
        /// </summary>
        /// <param name="url">The URL to send the DELETE request to.</param>
        /// <param name="headers">Optional headers to include in the request.</param>
        /// <param name="onSuccess">Callback invoked with success message on successful request.</param>
        /// <param name="onError">Callback invoked with error message on request failure.</param>
        public static void Delete(string url, Dictionary<string, string> headers, Action<string> onSuccess, Action<string> onError)
        {
            RequestRunner.Instance.StartCoroutine(DeleteCoroutine(url, headers, onSuccess, onError));
        }

        /// <summary>
        /// Coroutine for handling the DELETE request.
        /// </summary>
        private static IEnumerator DeleteCoroutine(string url, Dictionary<string, string> headers, Action<string> onSuccess, Action<string> onError)
        {
            using (UnityWebRequest webRequest = UnityWebRequest.Delete(url))
            {
                SetHeaders(webRequest, headers);
                yield return webRequest.SendWebRequest();

                if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
                {
                    onError?.Invoke(webRequest.error);
                }
                else
                {
                    // Check if the request was successful (no content expected in response for DELETE)
                    if (webRequest.responseCode == 204) // 204 No Content
                    {
                        onSuccess?.Invoke("Delete Request Executed Successfully!");
                    }
                    else
                    {
                        onSuccess?.Invoke($"Delete Request Successful with Response Code: {webRequest.responseCode}");
                    }
                }
            }
        }

        /// <summary>
        /// Sets custom headers for a UnityWebRequest instance.
        /// </summary>
        /// <param name="webRequest">The UnityWebRequest instance to set headers for.</param>
        /// <param name="headers">Dictionary containing headers to set.</param>
        private static void SetHeaders(UnityWebRequest webRequest, Dictionary<string, string> headers)
        {
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    if (header.Key.Equals("User-Agent", StringComparison.OrdinalIgnoreCase))
                    {
                        webRequest.SetRequestHeader("User-Agent", header.Value);
                    }
                    else
                    {
                        webRequest.SetRequestHeader(header.Key, header.Value);
                    }
                }
            }
        }

        /// <summary>
        /// Handles the response of a UnityWebRequest.
        /// </summary>
        /// <param name="webRequest">The UnityWebRequest instance to handle the response for.</param>
        /// <param name="onSuccess">Callback invoked with response text on successful request.</param>
        /// <param name="onError">Callback invoked with error message on request failure.</param>
        private static void HandleResponse(UnityWebRequest webRequest, Action<string> onSuccess, Action<string> onError)
        {
            if (webRequest.result == UnityWebRequest.Result.ConnectionError || webRequest.result == UnityWebRequest.Result.ProtocolError)
            {
                Debug.LogError($"Error: {webRequest.error}");
                onError?.Invoke(webRequest.error);
            }
            else
            {
                onSuccess?.Invoke(webRequest.downloadHandler.text);
            }
        }
    }
}
