package wtf.opal.client.renderer.image;

import java.io.InputStream;
import java.nio.ByteBuffer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import org.lwjgl.nanovg.NanoVG;
import wtf.opal.client.Constants;
import wtf.opal.client.renderer.NVGRenderer;
import wtf.opal.utility.misc.system.IOUtility;

@Environment(EnvType.CLIENT)
public final class NVGImageRenderer {
   private final ByteBuffer imageData;
   private final int imageHandle;

   public NVGImageRenderer(InputStream inputStream, int flags) {
      this.imageData = IOUtility.ioResourceToByteBuffer(inputStream, 524288);
      this.imageHandle = NanoVG.nvgCreateImageMem(Constants.VG, flags, this.imageData);
   }

   public NVGImageRenderer(InputStream inputStream) {
      this(inputStream, 0);
   }

   public void drawImage(float x, float y, float width, float height) {
      NanoVG.nvgImagePattern(Constants.VG, x, y, width, height, 0.0F, this.imageHandle, 1.0F, NVGRenderer.NVG_PAINT);
      NanoVG.nvgBeginPath(Constants.VG);
      NanoVG.nvgRect(Constants.VG, x, y, width, height);
      NanoVG.nvgImagePattern(Constants.VG, x, y, width, height, 0.0F, this.imageHandle, 1.0F, NVGRenderer.NVG_PAINT);
      NanoVG.nvgFillPaint(Constants.VG, NVGRenderer.NVG_PAINT);
      NanoVG.nvgFill(Constants.VG);
      NanoVG.nvgClosePath(Constants.VG);
   }

   public void drawImage(float x, float y, float width, float height, int colorOverlay) {
      NanoVG.nvgImagePattern(Constants.VG, x, y, width, height, 0.0F, this.imageHandle, 1.0F, NVGRenderer.NVG_PAINT);
      NanoVG.nvgBeginPath(Constants.VG);
      NanoVG.nvgRect(Constants.VG, x, y, width, height);
      NanoVG.nvgImagePattern(Constants.VG, x, y, width, height, 0.0F, this.imageHandle, 1.0F, NVGRenderer.NVG_PAINT);
      NVGRenderer.applyColor(colorOverlay, NVGRenderer.NVG_COLOR_1);
      NVGRenderer.NVG_PAINT.innerColor(NVGRenderer.NVG_COLOR_1);
      NanoVG.nvgFillPaint(Constants.VG, NVGRenderer.NVG_PAINT);
      NanoVG.nvgFill(Constants.VG);
      NanoVG.nvgClosePath(Constants.VG);
   }
}
