/*
 *   This file is a part of the SteamWar software.
 *
 *   Copyright (C) 2025 SteamWar.de-Serverteam
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU Affero General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 *   GNU Affero General Public License for more details.
 *
 *   You should have received a copy of the GNU Affero General Public License
 *   along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package de.steamwar.bausystem.world;

import de.steamwar.bausystem.BauSystem;
import de.steamwar.bausystem.CraftbukkitWrapper;
import de.steamwar.bausystem.commands.CommandTPSLimiter;
import de.steamwar.core.TPSWatcher;
import org.bukkit.Bukkit;

import java.util.function.Supplier;

public class TPSUtils {

    private TPSUtils() {
        throw new IllegalStateException("Utility Class");
    }

    private static boolean warp = true;
    private static long nanoOffset = 0;
    private static long nanoDOffset = 0;

    public static void disableWarp() {
        warp = false;
    }

    public static long getNanoOffset() {
        return nanoOffset;
    }

    private static long ticksSinceServerStart = 0;
    public static final Supplier<Long> currentTick = () -> ticksSinceServerStart;

    public static void init() {
        CraftbukkitWrapper.impl.initTPS();
        Bukkit.getScheduler().runTaskTimer(BauSystem.getPlugin(), () -> nanoOffset += nanoDOffset, 1, 1);
        Bukkit.getScheduler().runTaskTimer(BauSystem.getPlugin(), () -> ticksSinceServerStart++, 1, 1);
    }

    public static void setTPS(double tps) {
        double d = 50 - (50 / (tps / 20.0));
        nanoDOffset = Math.max(0, Math.min((long) (d * 1000000), 37500000));
    }

    public static boolean isWarpAllowed() {
        return warp;
    }

    public static boolean isWarping() {
        return nanoDOffset > 0;
    }

    public static double getTps(TPSWatcher.TPSType tpsType) {
        if (TPSUtils.isWarping())
            return TPSWatcher.getTPS(tpsType, Math.max(CommandTPSLimiter.getCurrentTPSLimit(), 20));
        return TPSWatcher.getTPS(tpsType);
    }

}
