package net.Chipperfluff.chipi.util;

import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.minecraft.server.MinecraftServer;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class TickScheduler {

    private static final List<ScheduledTask> TASKS = new LinkedList<>();
    private static boolean registered = false;

    public static void init() {
        if (registered) return;
        registered = true;

        ServerTickEvents.END_SERVER_TICK.register(TickScheduler::tick);
    }

    public static void schedule(int delayTicks, Runnable action) {
        TASKS.add(new ScheduledTask(delayTicks, action));
    }

    private static void tick(MinecraftServer server) {
        Iterator<ScheduledTask> it = TASKS.iterator();
        while (it.hasNext()) {
            ScheduledTask task = it.next();
            task.ticks--;

            if (task.ticks <= 0) {
                try {
                    task.action.run();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                it.remove();
            }
        }
    }

    private static class ScheduledTask {
        int ticks;
        Runnable action;

        ScheduledTask(int ticks, Runnable action) {
            this.ticks = ticks;
            this.action = action;
        }
    }
}
