package zenith.zov.utility.mixin.client;

import com.darkmagician6.eventapi.EventManager;
import net.minecraft.client.MinecraftClient;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import zenith.zov.base.events.impl.player.EventItemUseCooldown;
import zenith.zov.utility.interfaces.IMinecraft;

@Mixin({MinecraftClient.class})
public class ItemCooldownManagerMixin implements IMinecraft {
    @Shadow
    private int itemUseCooldown;

    @Inject(
        method = {"doItemUse"},
        at = {@At("HEAD")},
        cancellable = true
    )
    private void onItemUseHead(CallbackInfo ci) {
        if (mc.player != null && mc.world != null) {
            EventItemUseCooldown event = new EventItemUseCooldown(this.itemUseCooldown);
            EventManager.call(event);
            if (event.isCancelled()) {
                ci.cancel();
            } else if (event.getCooldown() != this.itemUseCooldown) {
                this.itemUseCooldown = event.getCooldown();
            }
        }
    }

    @Inject(
        method = {"doItemUse"},
        at = {@At("RETURN")},
        cancellable = true
    )
    private void onItemUseReturn(CallbackInfo ci) {
        if (mc.player != null && mc.world != null) {
            EventItemUseCooldown event = new EventItemUseCooldown(this.itemUseCooldown);
            EventManager.call(event);
            if (event.isCancelled()) {
                ci.cancel();
            } else if (event.getCooldown() != this.itemUseCooldown) {
                this.itemUseCooldown = event.getCooldown();
            }
        }
    }
}
