package land.chipmunk.chipmunkmod.modules;

import com.google.common.hash.Hashing;
import com.google.gson.JsonElement;
import land.chipmunk.chipmunkmod.ChipmunkMod;


import net.kyori.adventure.audience.Audience;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.text.Text;

import java.nio.charset.StandardCharsets;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CustomChat {
    private final MinecraftClient client;

    public static final CustomChat INSTANCE = new CustomChat(MinecraftClient.getInstance());

    public static final Pattern RACIST_PATTERN = Pattern.compile("nigga|nigger|i hate black", Pattern.CASE_INSENSITIVE);

    public boolean enabled = true;

    public String format;

    private Timer timer;

    private int total = 0;

    public CustomChat (MinecraftClient client) {
        this.client = client;

        reloadFormat();
    }

    public void init () {
        final TimerTask task = new TimerTask() {
            public void run () {
                tick();
            }
        };

        resetTotal();

        timer = new Timer();
        timer.schedule(task, 0, 50);
    }

    private void tick () {
        final ClientPlayNetworkHandler networkHandler = client.getNetworkHandler();

        if (networkHandler != null) return;

        resetTotal();
        cleanup();
    }

    public void resetTotal() {
        total = 0;
    }

    private void cleanup () {
        if (timer == null) return;

        timer.cancel();
        timer.purge();
    }

    public void reloadFormat () {
        final JsonElement formatString = ChipmunkMod.CONFIG.customChat.format;

        if (formatString == null) format = "{\"translate\":\"chat.type.text\",\"with\":[\"USERNAME\",\"MESSAGE\"]}";
        else format = formatString.toString();
    }

    public void chat (String message) {
        final ClientPlayerEntity player = client.player;

        try {
            final Matcher racistMatcher = RACIST_PATTERN.matcher(message);
            if (racistMatcher.matches()) {
                player.sendMessage(Text.literal("racism bad"));

                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!enabled || !player.hasPermissionLevel(2) || !player.isCreative()) {
            Chat.sendChatMessage(message, true);
            return;
        }

        final String username = MinecraftClient.getInstance().getSession().getUsername();

        final String sanitizedMessage = message
                .replace("\\", "\\\\")
                .replace("\"", "\\\"");

        final LegacyComponentSerializer serializer = LegacyComponentSerializer.legacyAmpersand();

        final String randomized = String.valueOf(Math.random());

        final Component deserialized = serializer.deserialize(message);
        final String messageWithColor = GsonComponentSerializer.gson().serialize(deserialized).replace("MESSAGE", randomized);

        final String key = ChipmunkMod.CONFIG.bots.chomens.formatKey;

        final String hash = key != null ?
                Hashing.sha256()
                    .hashString(key + total, StandardCharsets.UTF_8)
                    .toString()
                    .substring(0, 8) :
                "";

        total++;

        try {
//            final MutablePlayerListEntry entry = Players.INSTANCE.getEntry(client.getNetworkHandler().getProfile().getId());

//            final Component displayNameComponent = entry.displayName().asComponent();

//            final String prefix = GsonComponentSerializer.gson().serialize(Component.join(JoinConfiguration.separator(Component.empty()), displayNameComponent.children().get(0)));
//            final String displayName = GsonComponentSerializer.gson().serialize(Component.join(JoinConfiguration.separator(Component.empty()), displayNameComponent.children().get(1)));

            // TODO: make this code not ohio code.,.,
            String sanitizedFormat = format
//                        .replace("\"PREFIX\"", prefix)
//                        .replace("\"DISPLAYNAME\"", displayName)
                            .replace("USERNAME", username)
                            .replace("HASH", hash)
                            .replace("{\"text\":\"MESSAGE\"}", messageWithColor)
                            .replace("\"extra\":[\"MESSAGE\"],\"color\":", "\"extra\":[" + messageWithColor + "],\"color\":")
                            .replace("MESSAGE", sanitizedMessage.replaceAll("&.", ""))
                            .replace(randomized, "MESSAGE"); // ohio ohio

            CommandCore.INSTANCE.run((KaboomCheck.INSTANCE.isKaboom ? "minecraft:tellraw @a " : "tellraw @a ") + sanitizedFormat);
        } catch (Exception e) {
            if (client.player == null) return;
            ((Audience) client.player).sendMessage(Component.text(e.toString()).color(NamedTextColor.RED));
        }
    }
}
