package dev.photosync.platform.mixin;

import dev.photosync.mcapi.lifecycle.QuitGuard;
import net.minecraft.client.Minecraft;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;

/**
 * Holds the door while uploads finish.
 *
 * <p>{@code stop()} is the single funnel for leaving the game -- Quit Game, the
 * window close button and Alt+F4 all reach it -- and it is where the guard gets
 * asked. Refusing here leaves the client running normally, so the dialog the
 * guard puts up is interactive rather than a freeze.
 *
 * <p>The window button re-enters this every frame for as long as GLFW's close
 * flag stays set, so the guard and the dialog it opens both have to tolerate
 * being asked repeatedly.
 */
@Mixin(Minecraft.class)
public class QuitMixin {

    @Inject(method = "stop", at = @At("HEAD"), cancellable = true)
    private void photosync$confirmQuit(CallbackInfo callback) {
        if (!QuitGuard.get().mayQuit()) {
            callback.cancel();
        }
    }
}
