package io.github.lasercar.simplemention;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerChatTabCompleteEvent;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Events implements Listener {

    @EventHandler
    public void onChat(AsyncPlayerChatEvent event) {
        String message = event.getMessage();

        if (MessageParser.hasMentions(message)) {

            Pattern pattern = Pattern.compile("@(\\w+)");
            Matcher matcher = pattern.matcher(message);
            StringBuffer messageBuffer = new StringBuffer();

            while (matcher.find()) {
                String mention = matcher.group(1);

                Player[] playersMatched = PlayerMatcher.findAllByName(mention);

                if (playersMatched.length > 0) {
                    matcher.appendReplacement(messageBuffer, MessageParser.highlightMention(mention));

                    SoundManager.pingPlayers(playersMatched);
                }
            }
            matcher.appendTail(messageBuffer);

            event.setMessage(messageBuffer.toString());
        }
    }

    @EventHandler
    public void onTabComplete(PlayerChatTabCompleteEvent event) {
//        if (event.getLastToken().equals("@")) {
//            event.getTabCompletions().push(Bukkit.getOnlinePlayers());
//        }

        //DEBUG
        Bukkit.getLogger().info(event.getTabCompletions().toString());
        event.getTabCompletions().clear();
        Bukkit.getLogger().info(event.getTabCompletions().toString());
    }

}

@@ -280,16 +280,64 @@
 Event;%0A%0A
+import java.util.Set;%0Aimport java.util.TreeSet;%0A
 import j
@@ -1398,26 +1398,24 @@
 nt event) %7B%0A
-//
         if (
@@ -1439,25 +1439,29 @@
 n().
-equals(%22@%22)
+charAt(0) == '@'
 ) %7B%0A
-//
+%0A
     
@@ -1472,167 +1472,252 @@
     
-event.getTabCompletions().push(Bukkit.getOnlinePlayers());%0A//        %7D%0A%0A        //DEBUG%0A        Bukkit.getLogger().info(event.getTabCompletions().toString());%0A
+Set%3CString%3E names = new TreeSet%3CString%3E();%0A%0A            for (Player player : Bukkit.getOnlinePlayers()) %7B%0A                names.add(%22@%22 + player.getPlayerListName());%0A                names.add(%22@%22 + player.getDisplayName());%0A            %7D%0A%0A    
     
@@ -1767,32 +1767,12 @@
     
-Bukkit.getLogger().info(
+    
 even
@@ -1793,28 +1793,40 @@
 tions().
-toString());
+addAll(names);%0A        %7D
 %0A    %7D%0A%0A

Implement @ tab completion, but opens #1