package de.winniepat.citrus.utils;

import de.winniepat.citrus.Client;
import de.winniepat.citrus.cosmetics.capes.*;
import de.winniepat.citrus.cosmetics.capes.sync.CapeSyncManager;
import de.winniepat.citrus.cosmetics.wings.sync.WingSyncManager;
import de.winniepat.citrus.managers.*;
import net.minecraft.client.MinecraftClient;

import java.util.Timer;
import java.util.TimerTask;

public class RefreshUtil {

    public static void startPeriodicRankRefresh() {
        Timer timer = new Timer("Citrus-PeriodicRankRefresh", true);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    MinecraftClient mc = MinecraftClient.getInstance();
                    if (mc.getNetworkHandler() != null && mc.player != null) {
                        Client.debugLog("Background Rank Refresh Triggered");
                        RankManager.refreshRankIfChanged();
                    }
                } catch (Exception e) {
                    Client.debugLog("Error during Rank refresh: " + e.getMessage());
                }
            }
        }, 10000, 30000);
    }

    public static void startPeriodicRegisterCheck() {

        if (ClientRegistrationManager.isRegistered()) return;

        Timer timer = new Timer("Citrus-PeriodicRegisterCheck", true);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    ClientRegistrationManager.register();
                } catch (Exception e) {
                    Client.debugLog("Error during Registration refresh: " + e.getMessage());
                }
            }
        }, 10000, 30000);
    }

    public static void startPeriodicCapeSync() {
        Timer timer = new Timer("Citrus-PeriodicCapeSync", true);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                try {
                    CapeSyncManager.forceSyncNow();
                    CapeHandler.retryFailedCapes();
                    CapeSyncManager.SYNCED_CAPE_CACHE.clear();
                    Client.debugLog("Background Cape sync triggered");
                } catch (Exception e) {
                    Client.logger.error("Error during Cape sync: {}", e.getMessage());
                }
            }
        }, 10000, 30000);
    }

    public static void start() {
        startPeriodicRankRefresh();
        startPeriodicRegisterCheck();
        startPeriodicCapeSync();
    }

}
