using FishNet.Serializing;
using UnityEngine;

namespace _PROJECT.Components.Drawing
{
    public static class Texture2DSerializer
    {
        public static void WriteTexture2D(this Writer writer, Texture2D texture)
        {
            // Convert the Texture2D to a byte array using PNG format
            byte[] textureBytes = texture.EncodeToPNG();

            // Write the length of the byte array
            writer.WriteInt32(textureBytes.Length);

            // Write the byte array
            writer.WriteBytes(textureBytes, 0, textureBytes.Length);
        }

        public static Texture2D ReadTexture2D(this Reader reader)
        {
            // Read the length of the byte array
            int textureBytesLength = reader.ReadInt32();

            // Create a new byte array with the length
            byte[] textureBytes = new byte[textureBytesLength];

            // Read the byte array into the created buffer
            reader.ReadBytes(ref textureBytes, textureBytesLength);

            // Create a new Texture2D object
            Texture2D texture = new Texture2D(1024, 1024);

            // Load the texture data from the byte array
            if (texture.LoadImage(textureBytes))
            {
                // Return the reconstructed Texture2D
                return texture;
            }

            Debug.LogError("Failed to load texture from byte array");
            return null;
        }
    }
}