package com.nincraft.ninbot.components.common;

import club.minnced.discord.webhook.WebhookClient;
import club.minnced.discord.webhook.WebhookClientBuilder;
import club.minnced.discord.webhook.send.WebhookMessageBuilder;
import lombok.extern.log4j.Log4j2;
import lombok.val;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Icon;
import net.dv8tion.jda.api.entities.TextChannel;
import net.dv8tion.jda.api.entities.Webhook;
import net.dv8tion.jda.api.managers.WebhookManager;

import java.io.IOException;
import java.net.URL;
import java.util.Optional;
import java.util.concurrent.ExecutionException;

@Log4j2
public class WebhookHelper {

    public Optional<Webhook> getWebhookByName(Guild guild, TextChannel textChannel, String name) {
        val webhooks = guild.retrieveWebhooks().complete();
        for (val webhook : webhooks) {
            if (webhook.getName().equalsIgnoreCase(name) && webhook.getChannel().equals(textChannel)) {
                return Optional.of(webhook);
            }
        }
        return Optional.empty();
    }

    public void setWebhookIcon(String iconUrl, WebhookManager manager) {
        try {
            Icon icon = Icon.from(new URL(iconUrl).openStream());
            manager.setAvatar(icon).queue();
        } catch (IOException e) {
            log.error("Failed to grab avatar", e);
        }
    }

    public void sendMessage(String message, String webhookUrl) {
        WebhookMessageBuilder messageBuilder = new WebhookMessageBuilder();
        messageBuilder.append(message);
        WebhookClient client = new WebhookClientBuilder(webhookUrl).build();
        try {
            client.send(messageBuilder.build()).get();
        } catch (InterruptedException | ExecutionException e) {
            log.error("Failed to send webhook message", e);
        }
        client.close();
    }
}

@@ -264,24 +264,63 @@
 lombok.val;%0A
+import net.dv8tion.jda.api.Permission;%0A
 import net.d
@@ -702,16 +702,319 @@
 lper %7B%0A%0A
+    /**%0A     * Returns Optional of the webhook if found%0A     * @param guild the guild to check for the webhook%0A     * @param textChannel the text channel search%0A     * @param name name of the webhook%0A     * @return Optional of the webhook if the bot has Permission.MANAGE_WEBHOOKS and its found%0A     */%0A
     publ
@@ -1100,24 +1100,119 @@
 ing name) %7B%0A
+        if (guild.getSelfMember().getPermissions().contains(Permission.MANAGE_WEBHOOKS)) %7B%0A    
         val 
@@ -1255,24 +1255,28 @@
 complete();%0A
+    
         for 
@@ -1310,24 +1310,28 @@
             
+    
 if (webhook.
@@ -1418,32 +1418,36 @@
                 
+    
 return Optional.
@@ -1459,16 +1459,34 @@
 bhook);%0A
+                %7D%0A
         

Check for webhook permissions before getting a webhook