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

package engine.net.client.handlers;

import engine.gameManager.DispatchManager;
import engine.mbEnums.DispatchChannel;
import engine.net.client.ClientConnection;
import engine.net.client.msg.ClientNetMsg;
import engine.net.client.msg.RandomMsg;
import engine.objects.PlayerCharacter;
import engine.server.MBServerStatics;

import java.util.concurrent.ThreadLocalRandom;

public class RandomMsgHandler extends AbstractClientMsgHandler {

    public RandomMsgHandler() {
        super();
    }

    @Override
    protected boolean _handleNetMsg(ClientNetMsg baseMsg, ClientConnection origin) {

        // Member variable declaration

        RandomMsg msg = (RandomMsg) baseMsg;

        PlayerCharacter source = origin.getPlayerCharacter();

        if (source == null || !source.isAlive())
            return true;

        //2 second cooldown on random rolls
        long lastRandom = source.getTimeStamp("RandomRoll");

        if (System.currentTimeMillis() - lastRandom < 2000)
            return true;

        source.setTimeStamp("RandomRoll", System.currentTimeMillis());

        //handle random roll
        int max = msg.getMax();

        if (max > 0)
            msg.setRoll(ThreadLocalRandom.current().nextInt(max) + 1);
        else if (max < 0) {
            max = 1 - max;
            msg.setRoll((ThreadLocalRandom.current().nextInt(max) - max) + 1);
        }

        msg.setSourceType(source.getObjectType().ordinal());
        msg.setSourceID(source.getObjectUUID());

        //send to all in range
        DispatchManager.dispatchMsgToInterestArea(source, msg, DispatchChannel.SECONDARY, MBServerStatics.CHARACTER_LOAD_RANGE, true, true);

        return true;
    }

}