using System.Text;

#pragma warning disable IDE0130 // Namespace does not match folder structure
namespace ArmaDragonflyClient
#pragma warning restore IDE0130 // Namespace does not match folder structure
{
    internal class Utils
    {
        public static string Base64Decode(string encodedString)
        {
            byte[] data = Convert.FromBase64String(encodedString);
            return Encoding.UTF8.GetString(data);
        }

        public static string Base64Encode(string plainText)
        {
            byte[] data = Encoding.UTF8.GetBytes(plainText);
            return Convert.ToBase64String(data);
        }

        public static string BuildArray(string text)
        {
            string str = $"[\"{text}\"]";
            return str;
        }

        public static List<string> SplitIntoChunks(string data, int chunkSize)
        {
            int chunksNeeded = (int)Math.Ceiling((double)data.Length / chunkSize);
            List<string> chunks = [];

            for (int i = 0; i < chunksNeeded; i++)
            {
                int start = i * chunkSize;
                int end = Math.Min(data.Length, start + chunkSize);
                chunks.Add(data[start..end]);
            }

            return chunks;
        }

        public static long GetUniqueId()
        {
            return DateTimeOffset.Now.ToUnixTimeMilliseconds();
        }

        public static void CheckByteCount(string uniqueId, string data, string function, string entity, bool call, int bufferSize)
        {
            if (Encoding.UTF8.GetByteCount(data) <= bufferSize)
            {
                if (!data.StartsWith('['))
                    data = BuildArray(data);

                Main.Log($"Single chunk data: {data}", "debug");

                string dataAsString = $"[\"{uniqueId}\",\"{function}\",{call.ToString().ToLower()},{data},\"{entity}\"]";

                Main.Log($"Single chunk data string: {dataAsString}", "debug");
                Main.Callback("ArmaDragonflyClient", "dragonfly_db_fnc_handler", dataAsString);
            }
            else
            {
                if (!data.StartsWith('[') || !data.EndsWith(']'))
                    data = BuildArray(data);

                Main.Log($"Single chunk data: {data}", "debug");

                var chunks = SplitIntoChunks(data, bufferSize);
                int totalChunks = chunks.Count;

                for (int chunkIndex = 0; chunkIndex < chunks.Count; chunkIndex++)
                {
                    string escapedChunkData = chunks[chunkIndex].Replace("\"", "\"\"");
                    string chunkAsString = $"[\"{uniqueId}\",\"{function}\",{chunkIndex+1},{totalChunks},\"{escapedChunkData}\",{call.ToString().ToLower()},\"{entity}\"]";

                    Main.Log($"Chunk {chunkIndex+1}/{totalChunks}: {chunkAsString}", "debug");
                    Main.Callback("ArmaDragonflyClient", "dragonfly_db_fnc_fetch", chunkAsString);
                }
            }
        }

        public static void CheckByteCountPubSub(string uniqueId, string data, string eventType, string eventName, string target, int bufferSize)
        {
            if (Encoding.UTF8.GetByteCount(data) <= bufferSize)
            {
                if (!data.StartsWith('['))
                    data = BuildArray(data);

                Main.Log($"Single chunk data: {data}", "debug");

                string dataAsString = $"[\"{uniqueId}\",\"{eventType}\",\"{eventName}\",{data},\"{target}\"]";

                Main.Log($"Single chunk data: {dataAsString}", "debug");
                Main.Callback("ArmaDragonflyClient", "dragonfly_db_fnc_pubSubHandler", dataAsString);
            }
            else
            {
                if (!data.StartsWith('['))
                    data = BuildArray(data);

                Main.Log($"Single chunk data: {data}", "debug");

                var chunks = SplitIntoChunks(data, bufferSize);
                int totalChunks = chunks.Count;

                for (int chunkIndex = 0; chunkIndex < chunks.Count; chunkIndex++)
                {
                    string escapedChunkData = chunks[chunkIndex].Replace("\"", "\"\"");
                    string chunkAsString = $"[\"{uniqueId}\",\"{eventType}\",\"{eventName}\",{chunkIndex+1},{totalChunks},\"{escapedChunkData}\",\"{target}\"]";

                    Main.Log($"Chunk {chunkIndex+1}/{totalChunks}: {chunkAsString}", "debug");
                    Main.Callback("ArmaDragonflyClient", "dragonfly_db_fnc_pubSubFetch", chunkAsString);
                }
            }
        }
    }
}