package de.winniepat.citrus.cosmetics.wings;

import de.winniepat.citrus.cosmetics.wings.sync.WingSyncManager;
import de.winniepat.citrus.cosmetics.wings.sync.WingSyncManager.SyncedWingData;
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 CosmeticWings implements GeoAnimatable {
    private final AnimatableInstanceCache cache = GeckoLibUtil.createInstanceCache(this);
    private final PlayerEntity player;

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

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

    public WingType getWingType() {
        SyncedWingData syncedData =
                WingSyncManager.getSyncedWings(
                        player.getUuid(),
                        player.getName().getString()
                );

        if (syncedData != null && WingSyncManager.hasInitialSyncCompleted()) {
            return WingType.fromId(syncedData.wingType);
        }

        String wingId = ClientWingManager.getActiveWings(player.getUuid());
        return WingType.fromId(wingId);
    }

    public boolean shouldRender() {
        WingType type = getWingType();
        if (type == WingType.NONE) {
            return false;
        }

        SyncedWingData syncedData =
                WingSyncManager.getSyncedWings(
                        player.getUuid(),
                        player.getName().getString()
                );

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

        return ClientWingManager.areWingsVisible(player.getUuid()) && !player.isInvisible();
    }

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

            PlayerEntity p = state.getAnimatable().getPlayer();

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

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

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