package com.dairymoose.modernlife.items;

import com.dairymoose.entity.DummyEntity;
import com.dairymoose.modernlife.core.CustomBlocks;
import com.dairymoose.modernlife.core.ModernLifeNetwork;
import com.dairymoose.modernlife.network.play.client.ClientboundBulletHolePacket;
import com.dairymoose.modernlife.network.play.client.ServerboundHitscanPacket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.sounds.SoundEvents;
import net.minecraft.sounds.SoundSource;
import net.minecraft.tags.BlockTags;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.entity.projectile.ProjectileUtil;
import net.minecraft.world.item.DiggerItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import net.minecraft.world.item.Tier;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.material.Material;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import net.minecraft.world.phys.HitResult;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.network.PacketDistributor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/* loaded from: outputsrg.jar:com/dairymoose/modernlife/items/HandgunItem.class */
public class HandgunItem extends DiggerItem {
    public static final int FIRING_TICK_MAX = 6;
    public static final int RELOADING_TICK_MAX = 30;
    public static final float handgunZoomFactor = 1.5f;
    public static final float DESTROY_INCREMENT = 0.49f;
    public static int reloadingTick = -1;
    public static Map<Player, Integer> firingTickMap = new ConcurrentHashMap();
    public static long lastShotTimestamp = 0;
    public static double originalFov = -1.0d;
    public static Map<Player, MiningInfo> mineMap = new HashMap();
    private static final Logger LOGGER = LogManager.getLogger();

    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/items/HandgunItem$MiningInfo.class */
    public static class MiningInfo {
        public float miningInitialValue;
        public float miningValue;
        public BlockPos pos;
    }

    public HandgunItem(Tier p_i48530_1_, float p_i48530_2_, float p_i48530_3_, Properties p_i48530_4_) {
        super(p_i48530_2_, p_i48530_3_, p_i48530_1_, BlockTags.LEAVES, p_i48530_4_);
    }

    public boolean shouldCauseReequipAnimation(ItemStack oldStack, ItemStack newStack, boolean slotChanged) {
        return false;
    }

    public boolean onEntitySwing(ItemStack stack, LivingEntity entity) {
        return true;
    }

    public boolean onDroppedByPlayer(ItemStack item, Player player) {
        resetFov();
        return super.onDroppedByPlayer(item, player);
    }

    public void hitBlockPos(Player player, Level world, ItemStack itemStack, BlockPos pos, Vec3 loc, Direction direction) {
        BlockState state = world.getBlockState(pos);
        Material material = state.m_60767_();
        ItemStack stoneSword = new ItemStack(new ItemLike() { // from class: com.dairymoose.modernlife.items.HandgunItem.1
            C01291() {
            }

            public Item asItem() {
                return Items.STONE_SWORD;
            }
        });
        float speed = stoneSword.getItem().getDestroySpeed(stoneSword, state);
        boolean destroyed = false;
        if (speed >= 1.5f || material == Material.ICE) {
            world.m_46961_(pos, true);
            destroyed = true;
        } else {
            float destroySpeed = state.m_60800_(world, pos);
            MiningInfo mInfo = mineMap.get(player);
            if (mInfo == null) {
                mInfo = new MiningInfo();
                mineMap.put(player, mInfo);
            }
            if (!pos.equals(mInfo.pos)) {
                mInfo.pos = pos;
                if (destroySpeed < 0.0f) {
                    mInfo.pos = null;
                }
                mInfo.miningValue = destroySpeed;
                mInfo.miningInitialValue = destroySpeed;
            }
            if (mInfo.miningInitialValue > 0.0f) {
                mInfo.miningValue -= 0.49f;
            }
            if (mInfo.miningInitialValue > 0.0f) {
                if (mInfo.miningValue <= 0.0f) {
                    world.destroyBlockProgress(-1, pos, 10);
                    world.m_46961_(pos, true);
                    destroyed = true;
                    mInfo.pos = null;
                    mInfo.miningInitialValue = -1.0f;
                } else {
                    int progressVal = (int) (10.0d * (1.0d - (mInfo.miningValue / mInfo.miningInitialValue)));
                    world.destroyBlockProgress(-1, pos, progressVal);
                }
            }
        }
        if (!destroyed) {
            int holeNo = (int) (Math.random() * 3.0d);
            ModernLifeNetwork.INSTANCE.send(PacketDistributor.ALL.noArg(), new ClientboundBulletHolePacket(player.getId(), loc, pos, holeNo, direction, player.level.dimension().location().toString()));
        }
    }

    /* renamed from: com.dairymoose.modernlife.items.HandgunItem$1 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/items/HandgunItem$1.class */
    public class C01291 implements ItemLike {
        C01291() {
        }

        public Item asItem() {
            return Items.STONE_SWORD;
        }
    }

    public boolean hasAmmo(Player player) {
        for (int i = 0; i < player.getInventory().items.size(); i++) {
            ItemStack itemStack = (ItemStack) player.getInventory().items.get(i);
            if (itemStack != null && (itemStack.getItem() == CustomBlocks.ITEM_MAGAZINE.get() || itemStack.getItem() == CustomBlocks.ITEM_EXTENDED_MAGAZINE.get())) {
                return true;
            }
        }
        return false;
    }

    public boolean removeAmmo(Player player, int ammo) {
        for (int i = 0; i < player.getInventory().items.size(); i++) {
            ItemStack itemStack = (ItemStack) player.getInventory().items.get(i);
            if (itemStack != null && (itemStack.getItem() == CustomBlocks.ITEM_MAGAZINE.get() || itemStack.getItem() == CustomBlocks.ITEM_EXTENDED_MAGAZINE.get())) {
                itemStack.hurtAndBreak(ammo, player, new Consumer<Player>() { // from class: com.dairymoose.modernlife.items.HandgunItem.2
                    C01302() {
                    }

                    @Override // java.util.function.Consumer
                    public void accept(Player t) {
                    }
                });
                return true;
            }
        }
        return false;
    }

    /* renamed from: com.dairymoose.modernlife.items.HandgunItem$2 */
    /* loaded from: outputsrg.jar:com/dairymoose/modernlife/items/HandgunItem$2.class */
    public class C01302 implements Consumer<Player> {
        C01302() {
        }

        @Override // java.util.function.Consumer
        public void accept(Player t) {
        }
    }

    public int getCurrentMagazineAmmo(Player player) {
        for (int i = 0; i < player.getInventory().items.size(); i++) {
            ItemStack itemStack = (ItemStack) player.getInventory().items.get(i);
            if (itemStack != null && (itemStack.getItem() == CustomBlocks.ITEM_MAGAZINE.get() || itemStack.getItem() == CustomBlocks.ITEM_EXTENDED_MAGAZINE.get())) {
                int remaining = itemStack.getMaxDamage() - itemStack.getDamageValue();
                return remaining;
            }
        }
        return 0;
    }

    public int getCurrentMagazineCapacity(Player player) {
        for (int i = 0; i < player.getInventory().items.size(); i++) {
            ItemStack itemStack = (ItemStack) player.getInventory().items.get(i);
            if (itemStack != null && (itemStack.getItem() == CustomBlocks.ITEM_MAGAZINE.get() || itemStack.getItem() == CustomBlocks.ITEM_EXTENDED_MAGAZINE.get())) {
                return itemStack.getMaxDamage();
            }
        }
        return 0;
    }

    public int getAmmoTotal(Player player) {
        int total = 0;
        for (int i = 0; i < player.getInventory().items.size(); i++) {
            ItemStack itemStack = (ItemStack) player.getInventory().items.get(i);
            if (itemStack != null && (itemStack.getItem() == CustomBlocks.ITEM_MAGAZINE.get() || itemStack.getItem() == CustomBlocks.ITEM_EXTENDED_MAGAZINE.get())) {
                int remaining = itemStack.getMaxDamage() - itemStack.getDamageValue();
                total += remaining;
            }
        }
        return total;
    }

    public boolean fireGun(Player player) {
        long timeDiff = System.currentTimeMillis() - lastShotTimestamp;
        if (timeDiff < 275) {
            return false;
        }
        if (reloadingTick < 0 || (reloadingTick == 0 && timeDiff >= 2000)) {
            reloadingTick = -1;
            if (!hasAmmo(player)) {
                player.level.playSound(player, player.blockPosition(), SoundEvents.LEVER_CLICK, SoundSource.BLOCKS, 1.0f, 2.0f);
                return false;
            }
            int magAmmo = getCurrentMagazineAmmo(player);
            int totalAmmo = getAmmoTotal(player);
            lastShotTimestamp = System.currentTimeMillis();
            firingTickMap.put(player, 6);
            BlockHitResult rayTraceForPlayer = getRayTraceForPlayer(player.level, player, 500.0d);
            BlockPos pos = null;
            int entityId = -1;
            Vec3 location = rayTraceForPlayer.getLocation();
            Direction direction = null;
            if (rayTraceForPlayer instanceof BlockHitResult) {
                BlockHitResult blockRayTrace = rayTraceForPlayer;
                pos = blockRayTrace.getBlockPos();
                direction = blockRayTrace.getDirection();
            } else if (rayTraceForPlayer instanceof EntityHitResult) {
                EntityHitResult entityRayTrace = (EntityHitResult) rayTraceForPlayer;
                pos = entityRayTrace.getEntity().blockPosition();
                entityId = entityRayTrace.getEntity().getId();
            }
            ServerboundHitscanPacket.playGunSound(player.level, player, pos);
            if (magAmmo == 1 && totalAmmo > 1) {
                reloadingTick = 30;
            }
            ModernLifeNetwork.INSTANCE.sendToServer(new ServerboundHitscanPacket(pos, entityId, location, direction));
            return true;
        }
        return false;
    }

    private HitResult getRayTraceForPlayer(Level world, Player player, double range) {
        Vec3 entityPos = player.getEyePosition(1.0f);
        Vec3 targetPos = entityPos.add(player.getViewVector(1.0f).scale(range));
        double spreadFactor = 0.0d;
        if (1 != 0) {
            Vec3 movement = player.getDeltaMovement();
            double offsetFactor = 1800.0d;
            if (1 != 0 && !player.isUsingItem()) {
                offsetFactor = 1800.0d * 2.0d;
            }
            spreadFactor = ((movement.x * movement.x) + (movement.z * movement.z)) * offsetFactor;
        }
        if (1 != 0 && spreadFactor == 0.0d && !player.isUsingItem()) {
            spreadFactor = 4.0d;
        }
        if (spreadFactor != 0.0d) {
            targetPos = targetPos.add((Math.random() * spreadFactor) - (spreadFactor / 2.0d), 0.0d, (Math.random() * spreadFactor) - (spreadFactor / 2.0d));
        }
        HitResult rayTrace = world.clip(new ClipContext(entityPos, targetPos, ClipContext.Block.COLLIDER, ClipContext.Fluid.NONE, player));
        Vec3 Vec3 = player.getEyePosition(1.0f);
        double d1 = range * range;
        if (rayTrace != null) {
            d1 = rayTrace.getLocation().distanceToSqr(Vec3);
        }
        Vec3 Vec31 = player.getViewVector(1.0f);
        Vec3 Vec32 = Vec3.add(Vec31.x * range, Vec31.y * range, Vec31.z * range);
        if (1 != 0) {
            Vec32 = Vec32.add((Math.random() * spreadFactor) - (spreadFactor / 2.0d), 0.0d, (Math.random() * spreadFactor) - (spreadFactor / 2.0d));
        }
        AABB axisalignedbb = player.getBoundingBox().expandTowards(Vec31.scale(range)).inflate(1.0d, 1.0d, 1.0d);
        DummyEntity dummy = new DummyEntity(DummyEntity.DUMMY_ENTITY, world);
        HitResult entityHitResult = ProjectileUtil.getEntityHitResult(dummy, Vec3, Vec32, axisalignedbb, entity -> {
            return (entity == player || entity.isSpectator() || !entity.isPickable()) ? false : true;
        }, d1);
        if (entityHitResult != null) {
            entityHitResult.getEntity();
            Vec3 Vec33 = entityHitResult.getLocation();
            Vec3.distanceToSqr(Vec33);
            rayTrace = entityHitResult;
        }
        return rayTrace;
    }

    public void appendHoverText(ItemStack itemStack, @Nullable Level world, List<Component> text, TooltipFlag flag) {
        text.add(new TextComponent("Left click to fire"));
        text.add(new TextComponent("Right click to aim down sights"));
        text.add(new TextComponent(" * Requires at least one Magazine in order to shoot"));
    }

    public static void resetFov() {
        originalFov = -1.0d;
    }

    public boolean canContinueUsing(ItemStack oldStack, ItemStack newStack) {
        if (oldStack != newStack) {
            resetFov();
        }
        return super.canContinueUsing(oldStack, newStack);
    }

    public void releaseUsing(ItemStack itemStack, Level p_77615_2_, LivingEntity entity, int p_77615_4_) {
        if (entity instanceof Player) {
            Player player = (Player) entity;
            player.stopUsingItem();
            resetFov();
        }
    }

    public int getUseDuration(ItemStack stack) {
        return 72000;
    }

    public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand p_77659_3_) {
        ItemStack itemStack = player.getItemInHand(p_77659_3_);
        player.startUsingItem(p_77659_3_);
        if (world.isClientSide && originalFov < 0.0d) {
            originalFov = Minecraft.getInstance().options.fov;
        }
        return InteractionResultHolder.consume(itemStack);
    }
}
