package com.jagrosh.vortex.commands.general;

import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import java.time.format.DateTimeFormatter;
import net.dv8tion.jda.api.*;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;

public class ServerinfoCmd extends Command
{
    private final static String LINESTART = "\u25AB"; 
    private final static String GUILD_EMOJI = "\uD83D\uDDA5"; 
    
    public ServerinfoCmd()
    {
        this.name = "serverinfo";
        this.aliases = new String[]{"server","guildinfo"};
        this.help = "shows server info";
        this.botPermissions = new Permission[]{Permission.MESSAGE_EMBED_LINKS};
        this.guildOnly = true;
    }
    
    @Override
    protected void execute(CommandEvent event) 
    {
        Guild guild = event.getGuild();
        Member owner = guild.getOwner();
        
        // Note: Presence/Online status requires GUILD_PRESENCES intent
        long onlineCount = guild.getMemberCache().stream().filter(u -> u.getOnlineStatus() != OnlineStatus.OFFLINE).count();
        long botCount = guild.getMemberCache().stream().filter(m -> m.getUser().isBot()).count();
        
        EmbedBuilder builder = new EmbedBuilder();
        String title = (GUILD_EMOJI + " Information about **" + guild.getName() + "**:")
                .replace("@everyone", "@\u0435veryone") 
                .replace("@here", "@h\u0435re") 
                .replace("discord.gg/", "dis\u0441ord.gg/");

        String str = LINESTART + "ID: **" + guild.getId() + "**\n"
                + LINESTART + "Owner: " + (owner == null ? "Unknown" : "**" + owner.getUser().getName() + "**") + "\n"
                + LINESTART + "Creation: **" + guild.getTimeCreated().format(DateTimeFormatter.RFC_1123_DATE_TIME) + "**\n"
                + LINESTART + "Users: **" + guild.getMemberCount() + "** (" + onlineCount + " online, " + botCount + " bots)\n"
                + LINESTART + "Channels: **" + guild.getTextChannelCache().size() + "** Text, **" + guild.getVoiceChannelCache().size() + "** Voice, **" + guild.getCategoryCache().size() + "** Categories\n"
                + LINESTART + "Verification: **" + guild.getVerificationLevel().name() + "**";
                
        if(!guild.getFeatures().isEmpty())
            str += "\n" + LINESTART + "Features: **" + String.join("**, **", guild.getFeatures()) + "**";
            
        if(guild.getIconUrl() != null)
            builder.setThumbnail(guild.getIconUrl());
            
        builder.setColor(owner == null ? null : owner.getColor());
        builder.setDescription(str);
        
        event.reply(new MessageCreateBuilder().addContent(title).setEmbeds(builder.build()).build());
    }
}