package dev.crucifixbeta.mod.modules.impl.exploit;

import dev.crucifixbeta.api.events.eventbus.EventListener;
import dev.crucifixbeta.api.events.impl.PacketEvent;
import dev.crucifixbeta.api.events.impl.UpdateEvent;
import dev.crucifixbeta.api.utils.Wrapper;
import dev.crucifixbeta.api.utils.math.Timer;
import dev.crucifixbeta.mod.modules.Module;
import dev.crucifixbeta.mod.modules.settings.impl.SliderSetting;
import java.util.concurrent.CopyOnWriteArrayList;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.network.packet.Packet;
import net.minecraft.network.packet.s2c.common.CommonPingS2CPacket;
import net.minecraft.network.packet.s2c.common.KeepAliveS2CPacket;

@Environment(EnvType.CLIENT)
public class PingSpoof extends Module {
   final CopyOnWriteArrayList<PingSpoof.CustomPacket> packet = new CopyOnWriteArrayList<>();
   private final SliderSetting spoof = this.add(new SliderSetting("Spoof", 500.0, 0.0, 5000.0, 1.0).setSuffix("ms"));

   public PingSpoof() {
      super("PingSpoof", Module.Category.Exploit);
      this.setChinese("\u5ef6\u8fdf\u6b3a\u9a97");
   }

   @Override
   public void onLogout() {
      this.packet.clear();
   }

   @EventListener
   public void onPacketReceive(PacketEvent.Receive event) {
      if (!nullCheck()) {
         if (event.getPacket() instanceof CommonPingS2CPacket || event.getPacket() instanceof KeepAliveS2CPacket) {
            this.packet.add(new PingSpoof.CustomPacket(this, event.getPacket()));
            event.cancel();
         }
      }
   }

   @EventListener
   public void onUpdate(UpdateEvent event) {
      this.update();
   }

   @Override
   public void onRender3D(MatrixStack matrixStack) {
      this.update();
   }

   @Override
   public void onDisable() {
      if (nullCheck()) {
         this.packet.clear();
      } else {
         for (PingSpoof.CustomPacket var2 : this.packet) {
            var2.apply();
         }
      }
   }

   private void update() {
      if (nullCheck()) {
         this.packet.clear();
      } else {
         this.packet.removeIf(PingSpoof.CustomPacket::send);
      }
   }
@Environment(EnvType.CLIENT)
   private class CustomPacket {
      final Packet pp;
      final int delay;
      private final Timer timer;

      public CustomPacket(PingSpoof pingSpoof, Packet p) {
         this.pp = p;
         this.timer = new Timer();
         this.delay = pingSpoof.spoof.getValueInt();
      }

      public boolean send() {
         if (this.timer.passed((long)this.delay)) {
            try {
               this.apply();
            } catch (Exception var2) {
               var2.printStackTrace();
            }

            return true;
         } else {
            return false;
         }
      }

      public void apply() {
         if (this.pp != null) {
            this.pp.apply(Wrapper.mc.getNetworkHandler());
         }
      }
   }
}
