package de.winniepat.citrus;

import de.winniepat.citrus.beta.*;
import de.winniepat.citrus.cosmetics.*;
import de.winniepat.citrus.cosmetics.capes.*;
import de.winniepat.citrus.cosmetics.capes.sync.*;
import de.winniepat.citrus.client.*;
import de.winniepat.citrus.cosmetics.halo.HaloFeatureRenderer;
import de.winniepat.citrus.cosmetics.hat.HatFeatureRenderer;
import de.winniepat.citrus.cosmetics.wings.WingsFeatureRenderer;
import de.winniepat.citrus.cosmetics.wings.sync.*;
import de.winniepat.citrus.draggui.*;
import de.winniepat.citrus.gui.*;
import de.winniepat.citrus.managers.*;
import de.winniepat.citrus.utils.*;
import icyllis.modernui.mc.MuiModApi;
import net.fabricmc.fabric.api.client.rendering.v1.LivingEntityFeatureRendererRegistrationCallback;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.render.entity.PlayerEntityRenderer;
import org.slf4j.*;

import net.fabricmc.fabric.api.client.event.lifecycle.v1.*;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents;
import net.minecraft.client.MinecraftClient;
import net.minecraft.text.Text;

import java.io.*;

public class Client {

    public static final Logger logger = LoggerFactory.getLogger(Client.class);

    public static final String CLIENT_BUILD = "last";
    public static final String clientInfo = "Citrus 1.21-" + CLIENT_BUILD + " | Minecraft 1.21";

    public static final File CONFIG_DIR = new File(FabricLoader.getInstance().getGameDir().toFile(),"citrus");

    public static final boolean debug = true;
    public static final boolean betaFeaturesEnabled = false;

    public static final String API_URL = "https://api.citrus-client.de";
    public static final String CDN_URL = "https://cdn.citrus-client.de";
    public static final String BETA_URL = "https://beta.citrus-client.de";

    private static BetaManager betaManager;

    protected void init() throws IOException {

        betaManager = BetaManager.getInstance();

        betaManager.initialize();

        ClientCommands.register();
        ClientKeybinds.register();
        CosmeticCommands.register();

        CapeHandler.init();
        ConfigManager.load();
        HudConfig.load();
        HudRenderer.register();
        TestScreen.registerRenderer();

        CapeSyncManager.init();
        WingSyncManager.init();
        WingSyncManager.startAutoSync();
        WallpaperManager.init();

        ClientRegistrationManager.register();
        FriendManager.init();

        ChatSound.init();

        debugLog(SecurityUtils.getDailyKey());

        RefreshUtil.start();

        ClientPlayConnectionEvents.JOIN.register((handler, sender, client) -> {
            ClientRegistrationManager.register();
            client.execute(FriendManager::updateServerStatus);
        });

        ClientPlayConnectionEvents.DISCONNECT.register((handler, client) -> FriendManager.updateServerStatus());

        ClientLifecycleEvents.CLIENT_STOPPING.register(client -> ClientRegistrationManager.unregister());

        ClientTickEvents.END_CLIENT_TICK.register(client -> {
            if (client.world == null || client.player == null) return;

            PlayerCapeTracker.tick();

            while (ClientKeybinds.OPEN_CAPE_SCREEN.wasPressed() && client.player != null) {
                CapeHandler.reloadCapes();
                client.setScreen(new CapeSelectionScreen());
            }

            while (ClientKeybinds.OPEN_COSMETICS_SCREEN.wasPressed() && client.player != null) {
                client.setScreen(new CosmeticScreen());

                if (client.world != null || client.player != null){
                    PlayerCosmeticTracker.tick();
                }
            }

            while (ClientKeybinds.OPEN_FRIENDS_SCREEN.wasPressed() && client.player != null) {
                FriendManager.refresh();
                client.setScreen(MuiModApi.get().createScreen(new FriendsFragment(), null, client.currentScreen));
            }

            while (ClientKeybinds.OPEN_DRAGGUI.wasPressed()) {
                client.setScreen(MuiModApi.get().createScreen(new HudEditorFragment(), null, client.currentScreen));
            }

            while (ClientKeybinds.REFRESH_CLIENT.wasPressed() && client.player != null) {
                RankManager.refreshRankIfChanged();
                CapeHandler.reloadCapes();
                CapeHandler.retryFailedCapes();
                assert MinecraftClient.getInstance().player != null;
                MinecraftClient.getInstance().player.sendMessage(Text.literal("Refreshed Client"), false);
            }

            while (ClientKeybinds.TOGGLE_FULLBRIGHT.wasPressed()) {
                FullbrightManager.toggle(client);
            }

            while (ClientKeybinds.OPEN_MODULETOGGLE.wasPressed()) {
                client.setScreen(new ModuleToggleScreen());
            }

            while (ClientKeybinds.REFRESH_CLIENT.wasPressed()) {
                ClientRegistrationManager.forceUpdateOnlineUsers();
                CapeHandler.refreshCapeList();
                CapeHandler.retryFailedCapes();
            }

            if (client.world != null && client.player != null) {
                PlayerWingTracker.tick();
            }

            ZoomManager.setZooming(ClientKeybinds.ZOOM_KEY.isPressed());
        });

        LivingEntityFeatureRendererRegistrationCallback.EVENT.register((entityType, entityRenderer, registrationHelper, context) -> {
            if (entityRenderer instanceof PlayerEntityRenderer playerRenderer) {
                registrationHelper.register(new WingsFeatureRenderer(playerRenderer));
                registrationHelper.register(new HatFeatureRenderer(playerRenderer));
                registrationHelper.register(new HaloFeatureRenderer(playerRenderer));

                Client.debugLog("Registered cosmetic renderers for player");
            }
        });

        CosmeticSyncManager.init();
    }

    public static void debugLog(String message) {
        if (debug) {
            logger.info("[Citrus] [DEBUG] {}", message);
        }
    }

    public static BetaManager getBetaManager() {
        return betaManager;
    }
}