package net.voltexstudios.npcConversations.listener;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import net.voltexstudios.npcConversations.NPCConversations;
import net.voltexstudios.npcConversations.npc.NPC;
import net.voltexstudios.npcConversations.npc.NPCService;
import net.voltexstudios.npcConversations.session.ConverstionSession;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerMoveEvent;

public class PlayerListener implements Listener {

    @EventHandler
    public void onEntityInteract(PlayerInteractEntityEvent event) {
        NPC npc = NPCService.getInstance().getNPC(event.getRightClicked());
        if (npc == null) return;

        event.setCancelled(true);
        npc.onClick(event.getPlayer());
    }

    @EventHandler
    public void onMove(PlayerMoveEvent event) {
        if (NPCConversations.CACHE.asMap().containsKey(event.getPlayer())) {

            if (event.getFrom().getBlock().equals(event.getTo().getBlock())) return;

            ConverstionSession session = NPCConversations.CACHE.getIfPresent(event.getPlayer());
            if (session == null) return;

            NPC npc = session.getNpc();
            Entity entity = Bukkit.getEntity(npc.getClickableEntity());
            if (entity == null) return;

            if (event.getTo().distance(entity.getLocation()) > NPCConversations.getInstance().getConfig().getInt("npc-conversation-range", 5)) {
                NPCConversations.CACHE.invalidate(event.getPlayer());
                event.getPlayer().sendMessage(
                        NPCConversations.PREFIX.append(
                                Component.text("You have moved too far away from the NPC. The conversation has been cancelled.").color(NamedTextColor.RED)
                        )
                );
            }

        }
    }

}
