package net.wincorhq.changedsynergydowned.knockout;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.phys.Vec3;

public final class RecentDeaths {
    private static final long WINDOW_TICKS = 4L;
    private static final double MATCH_RANGE_SQR = 9.0D;

    private record Death(ServerLevel level, Vec3 pos, long tick, boolean lava) {}

    private static final List<Death> DEATHS = new ArrayList<>();

    private RecentDeaths() {}

    public static void record(ServerLevel level, Vec3 pos, boolean lava) {
        long now = level.getGameTime();
        prune(now);
        DEATHS.add(new Death(level, pos, now, lava));
    }

    public static Optional<Boolean> match(ServerLevel level, Vec3 pos) {
        prune(level.getGameTime());
        Iterator<Death> it = DEATHS.iterator();
        while (it.hasNext()) {
            Death death = it.next();
            if (death.level() == level && pos.distanceToSqr(death.pos()) <= MATCH_RANGE_SQR) {
                it.remove();
                return Optional.of(death.lava());
            }
        }
        return Optional.empty();
    }

    private static void prune(long now) {
        DEATHS.removeIf(d -> now - d.tick() > WINDOW_TICKS);
    }
}
