/*
 *   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.utils.tps;

import de.steamwar.Reflection;
import lombok.Getter;
import lombok.experimental.UtilityClass;
import org.bukkit.Bukkit;
import org.bukkit.World;

@UtilityClass
public class TPSFreezeUtils {

    private static Reflection.Field<Boolean> fieldAccessor;
    @Getter
    private static final boolean canFreeze;

    private static final Reflection.Method getWorldHandle = Reflection.getTypedMethod(Reflection.getClass("org.bukkit.craftbukkit.CraftWorld"), "getHandle", null);

    @Getter
    private static boolean frozen = false;

    private static final World world = Bukkit.getWorlds().get(0);

    static {
        Reflection.Field<Boolean> fieldAccessor;
        try {
            fieldAccessor = Reflection.getField(Reflection.getClass("net.minecraft.server.level.ServerLevel"), "freezed", boolean.class);
        } catch (IllegalArgumentException e) {
            fieldAccessor = null;
        }
        canFreeze = fieldAccessor != null;
        TPSFreezeUtils.fieldAccessor = fieldAccessor;
    }

    public void freeze() {
        setFreeze(world, true);
    }

    public void unfreeze() {
        setFreeze(world, false);
    }

    public boolean frozen() {
        return canFreeze && frozen;
    }

    private void setFreeze(World world, boolean state) {
        if (canFreeze) {
            fieldAccessor.set(getWorldHandle.invoke(world), state);
            if (state) {
                PacketCache.continuousSendCache();
            } else {
                PacketCache.clearCache();
            }
            frozen = state;
        }
    }
}
