package land.chipmunk.chipmunkmod.mixin;

import com.google.gson.JsonObject;
import land.chipmunk.chipmunkmod.ChipmunkMod;
import land.chipmunk.chipmunkmod.data.ChomeNSBotCommand;
import land.chipmunk.chipmunkmod.modules.ChomeNSBotCommandSuggestions;
import land.chipmunk.chipmunkmod.util.BotValidationUtilities;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.text.Text;
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 javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Mixin(value = net.minecraft.client.gui.screen.ChatScreen.class)
public class ChatScreenMixin extends Screen {
  @Shadow private String originalChatText;

  public ChatScreenMixin(String originalChatText) {
    super(Text.translatable("chat_screen.title"));
    this.originalChatText = originalChatText;
  }

  @Inject(method = "sendMessage", at = @At("HEAD"), cancellable = true)
  private void sendMessage (String chatText, boolean addToHistory, CallbackInfo cir) {
    final MinecraftClient client = MinecraftClient.getInstance();

    if (addToHistory) {
      client.inGameHud.getChatHud().addToMessageHistory(chatText);
    }

    if (ChipmunkMod.CONFIG.bots.testbot.webhookUrl != null && chatText.startsWith(ChipmunkMod.CONFIG.bots.testbot.prefix)) {
      ChipmunkMod.executorService.submit(() -> {
        try {
          final URL url = new URL(ChipmunkMod.CONFIG.bots.testbot.webhookUrl);

          final HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
          connection.addRequestProperty("Content-Type", "application/json");
          connection.addRequestProperty("User-Agent", "ChipmunkMod");
          connection.setDoOutput(true);
          connection.setRequestMethod("POST");

          final JsonObject jsonObject = new JsonObject();

          jsonObject.addProperty("username", "ChipmunkMod UwU");
          jsonObject.addProperty("content", MinecraftClient.getInstance().getSession().getUsername());

          final OutputStream stream = connection.getOutputStream();
          stream.write(jsonObject.toString().getBytes());
          stream.flush();
          stream.close();

          connection.getInputStream().close();
          connection.disconnect();
        } catch (IOException e) {
          e.printStackTrace();
        }
      });
    } else if (chatText.startsWith(ChipmunkMod.CONFIG.bots.chomens.prefix)) {
      final List<ChomeNSBotCommand> commands = ChomeNSBotCommandSuggestions.INSTANCE.commands;

      final List<String> moreOrTrustedCommands = commands.stream()
              .filter((command) -> command.trustLevel != ChomeNSBotCommand.TrustLevel.PUBLIC)
              .map((command) -> command.name.toLowerCase())
              .toList();

      final List<String> aliases = new ArrayList<>();
      for (ChomeNSBotCommand command : commands) {
        if (command.trustLevel == ChomeNSBotCommand.TrustLevel.PUBLIC) continue;

        aliases.addAll(command.aliases);
      }

      final String chatCommand = chatText.toLowerCase().split("\\s")[0];

      final int prefixLength = ChipmunkMod.CONFIG.bots.chomens.prefix.length();

      if (
              moreOrTrustedCommands.contains(chatCommand) ||
                      aliases.contains(chatCommand.substring(prefixLength))
      ) {
        try {
          BotValidationUtilities.chomens(chatText.substring(prefixLength));

          cir.cancel();

          return;
        } catch (Exception ignored) {}
      }
    }

    if (client == null) return;

    if (chatText.startsWith("/")) {
      client.player.networkHandler.sendChatCommand(chatText.substring(1));
    } else {
      client.player.networkHandler.sendChatMessage(chatText);
    }

    cir.cancel();
  }
}
