package wtf.opal.utility.misc.system;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import org.lwjgl.BufferUtils;
import org.lwjgl.system.MemoryUtil;

@Environment(EnvType.CLIENT)
public final class IOUtility {

   private IOUtility() {
   }

   public static ByteBuffer ioResourceToByteBuffer(InputStream inputStream, int bufferSize) {
      try {
         if (inputStream != null) {
            ByteBuffer var3;
            try (ReadableByteChannel var2 = Channels.newChannel(inputStream)) {
               var3 = BufferUtils.createByteBuffer(bufferSize);

               while (true) {
                  int var4 = var2.read(var3);
                  if (var4 == -1) {
                     break;
                  }

                  if (var3.remaining() == 0) {
                     var3 = resizeBuffer(var3, var3.capacity() * 3 / 2);
                  }
               }
            }

            var3.flip();
            return MemoryUtil.memSlice(var3);
         } else {
            throw new IllegalArgumentException("InputStream cannot be null");
         }
      } catch (IOException var8) {
         var8.printStackTrace();
         return null;
      }
   }

   private static ByteBuffer resizeBuffer(ByteBuffer buffer, int newCapacity) {
      ByteBuffer var2 = BufferUtils.createByteBuffer(newCapacity);
      buffer.flip();
      var2.put(buffer);
      return var2;
   }
}
