package com.vanamod.mod.items;

import com.vanamod.mod.VanaMod;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.world.World;

public class ItemHangGlider extends Item {

    private String textureName;

    public ItemHangGlider(String name) {
        this.textureName = name;
        this.setUnlocalizedName(name);
        this.setCreativeTab(VanaMod.vanaTab);
        this.setMaxStackSize(1);
    }

    @Override
    public ItemStack onItemRightClick(ItemStack stack, World world, EntityPlayer player) {
        // Toggle l'état du glider
        if (!stack.hasTagCompound()) {
            stack.setTagCompound(new NBTTagCompound());
        }

        boolean active = stack.getTagCompound().getBoolean("active");
        stack.getTagCompound().setBoolean("active", !active);

        return stack;
    }

    @Override
    public void onUpdate(ItemStack stack, World world, Entity entity, int slot, boolean isHeld) {
        if (entity instanceof EntityPlayer && isHeld) {
            EntityPlayer player = (EntityPlayer) entity;

            if (!stack.hasTagCompound()) {
                stack.setTagCompound(new NBTTagCompound());
            }

            boolean active = stack.getTagCompound().getBoolean("active");

            // Désactiver si au sol
            if (active && player.onGround) {
                stack.getTagCompound().setBoolean("active", false);
                return;
            }

            if (active && !player.onGround && player.motionY < 0) {
                // Boost horizontal vers l'avant
                double forward;
                if (player.isSneaking()) {
                    forward = 0.075; // Plus rapide avec Sneak
                    player.motionY *= 0.75;
                } else {
                    forward = 0.03; // Vitesse normale
                    player.motionY *= 0.6;
                }

                player.motionX += -Math.sin(Math.toRadians(player.rotationYaw)) * forward;
                player.motionZ += Math.cos(Math.toRadians(player.rotationYaw)) * forward;

                player.fallDistance = 0; // Annule dégâts de chute
            }
        }
    }

    @Override
    public boolean hasEffect(ItemStack stack) {
        // Glow seulement si actif
        if (!stack.hasTagCompound()) {
            return false;
        }
        return stack.getTagCompound().getBoolean("active");
    }

    @Override
    @SideOnly(Side.CLIENT)
    public void registerIcons(IIconRegister iconRegister) {
        this.itemIcon = iconRegister.registerIcon("vanamod:" + this.textureName);
    }
}