package com.loganmagnan.eventcore.listeners;

import com.loganmagnan.eventcore.EventCore;
import com.loganmagnan.eventcore.playerdata.PlayerData;
import com.loganmagnan.eventcore.utils.ColorUtils;
import com.loganmagnan.eventcore.utils.Constants;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;

public class AsyncPlayerChatListener implements Listener {

    private EventCore main = EventCore.getInstance();

    @EventHandler
    public void onAsyncPlayerChat(AsyncPlayerChatEvent event) {
        Player player = event.getPlayer();

        PlayerData playerData = this.main.getPlayerDataManager().getPlayerData(player.getUniqueId());

        if (this.main.getChatManager().isMuted()) {
            event.setCancelled(true);

            player.sendMessage(ColorUtils.getMessageType(Constants.LISTENER_MESSAGES.get("chat-muted").get(0)));

            return;
        }

        if (!player.hasPermission(Constants.PERMISSION_NODES.get("chat.bypass"))) {
            if (this.main.getCooldownManager().isOnChatCooldown(player.getUniqueId())) {
                int minutes = this.main.getCooldownManager().getChatCooldownTime(player.getUniqueId()) / 60;
                int seconds = this.main.getCooldownManager().getChatCooldownTime(player.getUniqueId()) % 60;

                event.setCancelled(true);

                for (String string : Constants.LISTENER_MESSAGES.get("chat-cooldown")) {
                    player.sendMessage(ColorUtils.getMessageType(string.replace("%time%", String.format("%02d:%02d", minutes, seconds))));
                }

                return;
            }
        }

        if (playerData.getChatColor() != null) {
            event.setMessage(playerData.getChatColor() + event.getMessage());
        }

        this.main.getCooldownManager().setChatCooldown(player.getUniqueId(), this.main.getChatManager().getDelayAmount());
    }
}
