package de.winniepat.citrus.cosmetics.hat;

import de.winniepat.citrus.cosmetics.CosmeticSyncManager;
import net.minecraft.entity.player.PlayerEntity;
import software.bernie.geckolib.animatable.GeoAnimatable;
import software.bernie.geckolib.animatable.instance.AnimatableInstanceCache;
import software.bernie.geckolib.animation.*;
import software.bernie.geckolib.util.GeckoLibUtil;

public class CosmeticHat implements GeoAnimatable {
    private final AnimatableInstanceCache cache = GeckoLibUtil.createInstanceCache(this);
    private final PlayerEntity player;

    public CosmeticHat(PlayerEntity player) {
        this.player = player;
    }

    public PlayerEntity getPlayer() {
        return this.player;
    }

    public HatType getHatType() {
        CosmeticSyncManager.SyncedCosmeticData syncedData =
                CosmeticSyncManager.getSyncedCosmetics(
                        player.getUuid(),
                        player.getName().getString()
                );

        if (syncedData != null && CosmeticSyncManager.hasInitialSyncCompleted()) {
            return HatType.fromId(syncedData.hatType);
        }

        String hatId = de.winniepat.citrus.cosmetics.ClientCosmeticManager.getActiveHat(player.getUuid());
        return HatType.fromId(hatId);
    }

    public boolean shouldRender() {
        HatType type = getHatType();
        if (type == HatType.NONE) {
            return false;
        }

        CosmeticSyncManager.SyncedCosmeticData syncedData =
                CosmeticSyncManager.getSyncedCosmetics(
                        player.getUuid(),
                        player.getName().getString()
                );

        if (syncedData != null && CosmeticSyncManager.hasInitialSyncCompleted()) {
            return syncedData.hatVisible && !player.isInvisible();
        }

        return de.winniepat.citrus.cosmetics.ClientCosmeticManager.isHatVisible(player.getUuid()) && !player.isInvisible();
    }

    @Override
    public void registerControllers(AnimatableManager.ControllerRegistrar controllers) {
        controllers.add(new AnimationController<>(this, "controller", 0, state -> {
            HatType type = state.getAnimatable().getHatType();
            if (type == HatType.NONE) {
                return null;
            }

            return state.setAndContinue(RawAnimation.begin().thenLoop("animation.hat.idle"));
        }));
    }

    @Override
    public AnimatableInstanceCache getAnimatableInstanceCache() {
        return this.cache;
    }

    @Override
    public double getTick(Object object) {
        return this.player.age;
    }
}