package de.fanta.challenges.utils.ChatSkullAPI;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextColor;
import org.bukkit.entity.Player;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
public class Message {
private final Component[] lines;
public Message(BufferedImage image, int height, char imgChar) {
TextColor[][] chatColors = toChatColorArray(image, height);
this.lines = toImgMessage(chatColors, imgChar);
}
public Message appendText(Component[] text) {
for (int y = 0; y < this.lines.length; y++) {
if (text.length > y) {
Component[] tmp16_12 = this.lines;
tmp16_12[y] = tmp16_12[y].append(text[y]);
}
}
return this;
}
private TextColor[][] toChatColorArray(BufferedImage image, int height) {
double ratio = ((double) image.getHeight() / image.getWidth());
BufferedImage resized = resizeImage(image, (int) (height / ratio), height);
TextColor[][] chatImg = new TextColor[resized.getWidth()][resized.getHeight()];
for (int x = 0; x < resized.getWidth(); x++) {
for (int y = 0; y < resized.getHeight(); y++) {
int rgb = resized.getRGB(x, y);
String hex = "#" + Integer.toHexString(rgb).substring(2);
TextColor closest = getClosestChatColor(TextColor.fromHexString(hex));
chatImg[x][y] = closest;
}
}
return chatImg;
}
private Component[] toImgMessage(TextColor[][] colors, char imgchar) {
Component[] lines = new Component[(colors[0]).length];
for (int y = 0; y < (colors[0]).length; y++) {
Component line = Component.empty();
for (TextColor[] textColors : colors) {
TextColor color = textColors[y];
line = line.append(Component.text(color != null ? imgchar : ' ', color != null ? textColors[y] : NamedTextColor.WHITE));
}
lines[y] = line;
}
return lines;
}
private BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
AffineTransform af = new AffineTransform();
af.scale(((double) width / originalImage.getWidth()), ((double) height / originalImage.getHeight()));
AffineTransformOp operation = new AffineTransformOp(af, 1);
return operation.filter(originalImage, null);
}
public void sendToPlayer(Player player) {
for (Component line : lines) {
player.sendMessage(line);
}
}
private TextColor getClosestChatColor(TextColor color) {
return color;
}
}