package dev.photosync.platform.mixin;

import com.mojang.blaze3d.platform.NativeImage;
import dev.photosync.core.capture.CaptureOrigin;
import dev.photosync.mcapi.capture.ScreenshotBus;
import net.minecraft.client.Screenshot;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Redirect;

import java.io.File;
import java.io.IOException;

/**
 * Notices the player pressing F2.
 *
 * <p>The redirect is on the write rather than on {@code grab}, because the write
 * is the only point at which the final path is known -- and because on every
 * supported version that call sits inside a synthetic lambda whose name changes
 * from release to release. Matching {@code method = "*"} against the invocation
 * sidesteps the name entirely; see docs/PORTING.md.
 *
 * <p>Announcing after the write, not before, means a listener that reads the
 * file back finds it there.
 */
@Mixin(Screenshot.class)
public class CaptureMixin {

    @Redirect(
            method = "*",
            at = @At(
                    value = "INVOKE",
                    target = "Lcom/mojang/blaze3d/platform/NativeImage;writeToFile(Ljava/io/File;)V"))
    private static void photosync$announceScreenshot(NativeImage image, File file) throws IOException {
        image.writeToFile(file);
        ScreenshotBus.get().published(file.toPath(), CaptureOrigin.MANUAL);
    }
}
