package com.tiedup.remake.util.time;

import net.minecraft.world.level.Level;

/**
 *
 * Unlike the original mod which used wall-clock time (Date objects),
 * this uses Minecraft game ticks for:
 * - Better security (can't exploit by changing system time)
 * - Respect for server TPS
 * - Easier debugging and testing
 *
 * Based on original Timer from 1.12.2 but modernized for 1.20.1
 */
public class Timer {

    private final long startTick; // Game time when timer started
    private final int ticksToWait; // Total ticks to wait
    private final Level level; // World reference for getting current game time

    /**
     * Create a new timer that counts down from the specified number of seconds.
     *
     * @param seconds Number of seconds to wait
     * @param level The world (used to get current game time)
     */
    public Timer(int seconds, Level level) {
        this.level = level;
        this.startTick = level.getGameTime();
        this.ticksToWait = seconds * 20; // Convert seconds to ticks (20 ticks/second)
    }

    /**
     * Get the number of ticks remaining until the timer expires.
     *
     * @return Remaining ticks (0 or negative if expired)
     */
    public int getTicksRemaining() {
        long currentTick = level.getGameTime();
        long elapsed = currentTick - startTick;
        return ticksToWait - (int) elapsed;
    }

    /**
     * Get the number of seconds remaining until the timer expires.
     *
     * @return Remaining seconds (0 or negative if expired)
     */
    public int getSecondsRemaining() {
        return getTicksRemaining() / 20;
    }

    /**
     * Check if the timer has expired.
     *
     * @return true if timer has run out
     */
    public boolean isExpired() {
        return getTicksRemaining() <= 0;
    }

    /**
     * Get elapsed time in ticks since timer started.
     *
     * @return Elapsed ticks
     */
    public int getElapsedTicks() {
        long currentTick = level.getGameTime();
        return (int) (currentTick - startTick);
    }

    /**
     * Get elapsed time in seconds since timer started.
     *
     * @return Elapsed seconds
     */
    public int getElapsedSeconds() {
        return getElapsedTicks() / 20;
    }

    /**
     * Get total duration in seconds.
     *
     * @return Total seconds
     */
    public int getTotalSeconds() {
        return ticksToWait / 20;
    }
}
