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

package engine.net.client.handlers;

import engine.exception.MsgSendException;
import engine.mbEnums.DispatchChannel;
import engine.net.DispatchMessage;
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(RandomMsg.class);
    }

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

        // 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
        DispatchMessage.dispatchMsgToInterestArea(source, msg, DispatchChannel.SECONDARY, MBServerStatics.CHARACTER_LOAD_RANGE, true, true);

        return true;
    }

}