package de.steamwar.cursor;

import com.comphenix.tinyprotocol.TinyProtocol;
import de.steamwar.core.Core;
import de.steamwar.core.SWPlayer;
import de.steamwar.linkage.Linked;
import lombok.Getter;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerInteractEvent;

import java.util.Optional;


@Linked
public class CursorListener implements Listener {
    @Getter
    private static CursorListener instance;

    public CursorListener() {
        if (instance == null) {
            instance = this;
        }

        TinyProtocol.instance.addFilter(ServerboundMovePlayerPacket.Pos.class, this::updateCursorFromPacket);
        TinyProtocol.instance.addFilter(ServerboundMovePlayerPacket.Rot.class, this::updateCursorFromPacket);
        TinyProtocol.instance.addFilter(ServerboundMovePlayerPacket.PosRot.class, this::updateCursorFromPacket);

        Bukkit.getScheduler().runTaskTimer(Core.getInstance(), () -> {
            SWPlayer.allWithSingleComponent(Cursor.class)
                    .map(SWPlayer.SWPlayerWithComponent::getComponent)
                    .forEach(Cursor::renderDeduplicated);
        }, 1, 1);
    }

    public Packet<?> updateCursorFromPacket(Player player, Packet<?> packet) {
        SWPlayer swPlayer = SWPlayer.of(player);
        Optional<Cursor> activeCursor = swPlayer.getComponent(Cursor.class);

        activeCursor.ifPresent(Cursor::renderDeduplicated);

        return packet;
    }

    @EventHandler
    public void onPlayerInteract(PlayerInteractEvent event) {
        SWPlayer.of(event.getPlayer()).getComponent(Cursor.class).ifPresent(cursor -> {
            event.setCancelled(true);
            cursor.handlePlayerClick(event.getAction());
        });
    }
}
