package com.firefrostgaming.rules;

import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegisterCommandsEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.ModLoadingContext;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.config.ModConfig;
import net.minecraftforge.fml.event.config.ModConfigEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Mod("firefrostrules")
public class ServerRules {
    private static final Logger LOGGER = LoggerFactory.getLogger(ServerRules.class);

    public ServerRules() {
        ModLoadingContext.get().registerConfig(ModConfig.Type.COMMON, ServerRulesConfig.SPEC);
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigLoaded);
        FMLJavaModLoadingContext.get().getModEventBus().addListener(this::onConfigReload);
        MinecraftForge.EVENT_BUS.register(this);
        LOGGER.info("Firefrost Rules Mod Initialized.");
    }

    @SubscribeEvent
    public void onRegisterCommands(RegisterCommandsEvent event) {
        RulesCommand.register(event.getDispatcher());
        LOGGER.info("Registered /rules command.");
    }

    @SubscribeEvent
    public void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent event) {
        CooldownManager.removePlayer(event.getPlayer().getUUID());
    }

    private void onConfigLoaded(ModConfigEvent.Loading event) {
        if (event.getConfig().getSpec() == ServerRulesConfig.SPEC) {
            String token = ServerRulesConfig.BOT_TOKEN.get();
            if (token.equals("YOUR_TOKEN_HERE")) {
                LOGGER.warn("Rules mod is using default config values! Edit config/firefrostrules-common.toml");
            } else {
                LOGGER.info("Rules mod config loaded successfully. Channel: {}", ServerRulesConfig.CHANNEL_ID.get());
            }
        }
    }

    private void onConfigReload(ModConfigEvent.Reloading event) {
        LOGGER.info("Rules configuration reloaded! Invalidating cache.");
        RulesCache.invalidate();
    }
}
