// • ▌ ▄ ·.  ▄▄▄·  ▄▄ • ▪   ▄▄· ▄▄▄▄·  ▄▄▄·  ▐▄▄▄  ▄▄▄ .
// ·██ ▐███▪▐█ ▀█ ▐█ ▀ ▪██ ▐█ ▌▪▐█ ▀█▪▐█ ▀█ •█▌ ▐█▐▌·
// ▐█ ▌▐▌▐█·▄█▀▀█ ▄█ ▀█▄▐█·██ ▄▄▐█▀▀█▄▄█▀▀█ ▐█▐ ▐▌▐▀▀▀
// ██ ██▌▐█▌▐█ ▪▐▌▐█▄▪▐█▐█▌▐███▌██▄▪▐█▐█ ▪▐▌██▐ █▌▐█▄▄▌
// ▀▀  █▪▀▀▀ ▀  ▀ ·▀▀▀▀ ▀▀▀·▀▀▀ ·▀▀▀▀  ▀  ▀ ▀▀  █▪ ▀▀▀
//      Magicbane Emulator Project © 2013 - 2022
//                www.magicbane.com


package engine.net;

import engine.objects.PlayerCharacter;

import java.util.concurrent.ConcurrentLinkedQueue;

import static engine.net.MessageDispatcher.itemPoolSize;

/**
 * Data class holds a message and a distribution list
 */

public class Dispatch {

    private static final ConcurrentLinkedQueue<Dispatch> dispatchPool = new ConcurrentLinkedQueue<>();

    public PlayerCharacter player;
    public AbstractNetMsg msg;

    public Dispatch(PlayerCharacter player, AbstractNetMsg msg) {
        this.player = player;
        this.msg = msg;
    }

    public static Dispatch borrow(PlayerCharacter player, AbstractNetMsg msg) {

        Dispatch dispatch;

        dispatch = dispatchPool.poll();

        if (dispatch == null) {
            dispatch = new Dispatch(player, msg);
        } else {
            dispatch.player = player;
            dispatch.msg = msg;
            itemPoolSize.decrement();
        }

        return dispatch;
    }

    public void reset() {
        this.player = null;
        this.msg = null;
    }

    public void release() {
        this.reset();
        dispatchPool.add(this);
        itemPoolSize.increment();
    }
}