package com.jagrosh.vortex.commands.general;

import java.time.format.DateTimeFormatter;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.commons.utils.FinderUtil;
import com.jagrosh.vortex.Emoji;
import com.jagrosh.vortex.utils.FormatUtil;
import com.jagrosh.vortex.utils.OtherUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.User;

public class UserinfoCmd extends Command
{
    private final static String USER_EMOJI = "\uD83D\uDC64"; 
    private final static String LINESTART = "\u2192"; 
    
    public UserinfoCmd()
    {
        this.name = "userinfo";
        this.aliases = new String[]{"user","uinfo","memberinfo"};
        this.help = "shows info on a member";
        this.arguments = "[user]";
        this.guildOnly = true;
        this.botPermissions = new Permission[]{Permission.MESSAGE_EMBED_LINKS};
    }
    
    @Override
    protected void execute(CommandEvent event) 
    {
        Member member;
        if(event.getArgs().isEmpty())
        {
            member = event.getMember();
        }
        else
        {
            List<Member> found = FinderUtil.findMembers(event.getArgs(), event.getGuild());
            if(found.isEmpty())
            {
                event.replyError("I couldn't find the member you were looking for!");
                return;
            }
            else if(found.size() > 1)
            {
                event.replyWarning(FormatUtil.filterEveryone(FormatUtil.listOfMember(found, event.getArgs())));
                return;
            }
            else
            {
                member = found.get(0);
            }
        }
        
        User user = member.getUser();
        String title = (user.isBot() ? Emoji.BOT : USER_EMOJI) + " Information about **" + user.getName() + "**:";
        StringBuilder str = new StringBuilder(LINESTART + "Discord ID: **" + user.getId() + "** ");
        user.getFlags().forEach(flag -> str.append(OtherUtil.getEmoji(flag)));
        
        if(user.getAvatarId() != null && user.getAvatarId().startsWith("a_"))
            str.append(Emoji.BADGE_NITRO);
        if(member.getNickname() != null)
            str.append("\n" + LINESTART + "Nickname: **").append(member.getNickname()).append("**");
            
        String roles = "";
        roles = member.getRoles().stream().map((rol) -> "`, `"+rol.getName()).reduce(roles, String::concat);
        if(roles.isEmpty())
            roles = "None";
        else
            roles = roles.substring(3) + "`";
            
        str.append("\n" + LINESTART + "Roles: ").append(roles);
        str.append("\n" + LINESTART + "Account Creation: **").append(user.getTimeCreated().format(DateTimeFormatter.RFC_1123_DATE_TIME)).append("**");
        
        // Safeguarded from OOM using Cache fallback instead of live array mapping
        List<Member> joins = new ArrayList<>(event.getGuild().getMemberCache().asList());
        Collections.sort(joins, (Member a, Member b) -> a.getTimeJoined().compareTo(b.getTimeJoined()));
        int index = joins.indexOf(member);
        
        str.append("\n" + LINESTART + "Guild Join Date: **").append(member.getTimeJoined().format(DateTimeFormatter.RFC_1123_DATE_TIME)).append("** `(#").append(index+1).append(")`");
        
        index -= 3;
        if(index < 0)
            index = 0;
            
        str.append("\n" + LINESTART + "Join Order: ");
        if(joins.get(index).equals(member))
            str.append("**").append(joins.get(index).getUser().getName()).append("**");
        else
            str.append(joins.get(index).getUser().getName());
            
        for(int i = index + 1; i < index + 7; i++)
        {
            if(i >= joins.size())
                break;
            Member m = joins.get(i);
            String uname = m.getUser().getName();
            if(m.equals(member))
                uname = "**" + uname + "**";
            str.append(" > ").append(uname);
        }
        
        event.reply(new MessageCreateBuilder()
                .addContent(FormatUtil.filterEveryone(title))
                .setEmbeds(new EmbedBuilder()
                        .setDescription(str.toString())
                        .setThumbnail(user.getEffectiveAvatarUrl())
                        .setColor(member.getColor()).build())
                .build());
    }
}