package com.dairymoose.modernlife.items;

import com.dairymoose.modernlife.blocks.PhotonBlock;
import com.dairymoose.modernlife.core.CustomBlocks;
import com.dairymoose.modernlife.core.ModernLifeCommon;
import com.dairymoose.modernlife.core.ModernLifeConfig;
import com.dairymoose.modernlife.core.ModernLifeNetwork;
import com.dairymoose.modernlife.network.play.client.ClientboundFlashlightUpdatePacket;
import com.dairymoose.modernlife.tileentities.PhotonBlockEntity;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.annotation.Nullable;
import net.minecraft.client.Minecraft;
import net.minecraft.core.BlockPos;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
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.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.DiggerItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Tier;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.ClipContext;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.properties.BlockStateProperties;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.phys.BlockHitResult;
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/FlashlightItem.class */
public class FlashlightItem extends DiggerItem {
    private int tickUpdatePeriod;
    private Set<Player> canRelease;
    private final Random random;
    private static final Logger LOGGER = LogManager.getLogger();
    public static Map<Player, Boolean> usingFlashlight = new HashMap();

    public FlashlightItem(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_);
        this.tickUpdatePeriod = 4;
        this.canRelease = new HashSet();
        this.random = new Random();
    }

    public boolean onDroppedByPlayer(ItemStack item, Player player) {
        usingFlashlight.put(player, false);
        removePhoton(player);
        return super.onDroppedByPlayer(item, player);
    }

    private boolean tryAddPhoton(Level world, Vec3 scaledView, LivingEntity livingEntity) {
        Vec3 entityPos = livingEntity.getEyePosition(1.0f);
        BlockHitResult result = world.clip(new ClipContext(entityPos, entityPos.add(scaledView), ClipContext.Block.OUTLINE, ClipContext.Fluid.NONE, livingEntity));
        Vec3 photonPos = result.getLocation();
        BlockPos photonBlockPos = new BlockPos(photonPos.x, photonPos.y, photonPos.z);
        BlockState state = world.getBlockState(photonBlockPos);
        if (state.is(CustomBlocks.BLOCK_PHOTON.get())) {
            if (!((Boolean) state.getValue(PhotonBlock.EXTINGUISHED)).booleanValue()) {
                return true;
            }
            world.setBlock(photonBlockPos, (BlockState) state.setValue(PhotonBlock.EXTINGUISHED, false), 2);
            return true;
        }
        boolean isWater = state.getFluidState() != null && state.getFluidState().is(Fluids.WATER) && state.getOptionalValue(BlockStateProperties.WATERLOGGED).isEmpty() && state.is(Blocks.WATER);
        if (state.isAir() || isWater) {
            world.setBlock(photonBlockPos, (BlockState) CustomBlocks.BLOCK_PHOTON.get().defaultBlockState().setValue(PhotonBlock.WATERLOGGED, Boolean.valueOf(isWater)), 2);
            removePhoton(livingEntity);
            PhotonBlockEntity.existingPhotons.add(photonBlockPos);
            PhotonBlockEntity.photonPos.put(livingEntity, photonBlockPos);
            return true;
        }
        return false;
    }

    public void onUsingTick(ItemStack itemStack, LivingEntity livingEntity, int count) {
        Integer configUpdatePeriod = (Integer) ModernLifeConfig.SERVER.flashlightUpdatePeriod.get();
        if (configUpdatePeriod != null) {
            this.tickUpdatePeriod = configUpdatePeriod.intValue();
        }
        if (count % this.tickUpdatePeriod == 0 && (livingEntity.level instanceof ServerLevel)) {
            if (itemStack.getDamageValue() < itemStack.getMaxDamage()) {
                Level world = livingEntity.level;
                Vec3 view = livingEntity.getViewVector(1.0f);
                float scaleValue = 6.0f;
                Double configRange = (Double) ModernLifeConfig.SERVER.flashlightRange.get();
                if (configRange != null) {
                    scaleValue = configRange.floatValue();
                }
                while (scaleValue >= 0.0f) {
                    Vec3 scaledView = view.scale(scaleValue);
                    if (tryAddPhoton(world, scaledView, livingEntity)) {
                        break;
                    } else {
                        scaleValue -= 1.0f;
                    }
                }
                itemStack.hurt(this.tickUpdatePeriod, this.random, (ServerPlayer) null);
                if (itemStack.getDamageValue() >= itemStack.getMaxDamage()) {
                    itemStack.setDamageValue(itemStack.getMaxDamage());
                    if (livingEntity instanceof Player) {
                        Player player = (Player) livingEntity;
                        usingFlashlight.put(player, false);
                        removePhoton(livingEntity);
                        return;
                    }
                    return;
                }
                return;
            }
            removePhoton(livingEntity);
        }
    }

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

    public void appendHoverText(ItemStack itemStack, @Nullable Level world, List<Component> text, TooltipFlag flag) {
        String currentMinutes = String.valueOf((int) Math.floor((itemStack.getMaxDamage() - itemStack.getDamageValue()) / 1200.0d));
        String maxMinutes = String.valueOf(itemStack.getMaxDamage() / 1200);
        text.add(new TextComponent("Right click to use"));
        text.add(new TextComponent("* Using it will deplete the battery but it will not break"));
        text.add(new TextComponent("* " + currentMinutes + " minutes remaining before drained"));
        text.add(new TextComponent("* Lasts " + maxMinutes + " minutes at full charge"));
        text.add(new TextComponent("* Repair durability by using a battery"));
    }

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

    public void inventoryTick(ItemStack itemStack, Level p_77663_2_, Entity p_77663_3_, int p_77663_4_, boolean p_77663_5_) {
    }

    public void releaseUsing(ItemStack itemStack, Level world, LivingEntity livingEntity, int p_77615_4_) {
        if ((world instanceof ServerLevel) && (livingEntity instanceof Player)) {
            Player player = (Player) livingEntity;
            if (this.canRelease.contains(player)) {
                this.canRelease.remove(player);
                world.playSound((Player) null, livingEntity.blockPosition(), SoundEvents.LEVER_CLICK, SoundSource.BLOCKS, 0.3f, 1.0f);
                ModernLifeCommon.LOGGER.debug("releaseUsing: " + world);
                removePhoton(player);
                return;
            }
            this.canRelease.add(player);
        }
    }

    public void removePhoton(LivingEntity livingEntity) {
        BlockPos entityPhoton = PhotonBlockEntity.photonPos.get(livingEntity);
        if (entityPhoton != null) {
            PhotonBlockEntity.existingPhotons.remove(entityPhoton);
            PhotonBlockEntity.photonPos.remove(livingEntity);
        }
    }

    public InteractionResultHolder<ItemStack> use(Level world, Player player, InteractionHand p_77659_3_) {
        ItemStack itemStack = player.getItemInHand(p_77659_3_);
        if (world.isClientSide && !player.equals(Minecraft.getInstance().player)) {
            InteractionResultHolder.consume(itemStack);
        }
        Boolean result = usingFlashlight.get(player);
        if (result == null) {
            result = false;
        }
        Boolean result2 = Boolean.valueOf(!result.booleanValue());
        if (itemStack.getDamageValue() >= itemStack.getMaxDamage()) {
            result2 = false;
        }
        ModernLifeCommon.LOGGER.debug("flashlight state=" + result2);
        world.playSound((Player) null, player.blockPosition(), SoundEvents.LEVER_CLICK, SoundSource.BLOCKS, 0.3f, 1.0f);
        if (world instanceof ServerLevel) {
            if (!result2.booleanValue()) {
                removePhoton(player);
            }
            usingFlashlight.put(player, result2);
            ModernLifeNetwork.INSTANCE.send(PacketDistributor.ALL.noArg(), new ClientboundFlashlightUpdatePacket(player.getId(), result2.booleanValue()));
            if (player.isUsingItem()) {
            }
        }
        return InteractionResultHolder.consume(itemStack);
    }
}
