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

package engine.net.client.handlers;

import engine.gameManager.SessionManager;
import engine.math.Vector3fImmutable;
import engine.net.client.ClientConnection;
import engine.net.client.msg.ClientNetMsg;
import engine.net.client.msg.PromptRecallMsg;
import engine.objects.Building;
import engine.objects.PlayerCharacter;
import engine.objects.Runegate;

import static engine.math.FastMath.sqr;

public class PromptRecallMsgHandler extends AbstractClientMsgHandler {

    public PromptRecallMsgHandler() {
        super();
    }

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

        // Member variable assignment

        PromptRecallMsg msg = (PromptRecallMsg) baseMsg;
        PlayerCharacter player = SessionManager.getPlayerCharacter(origin);
        boolean recallAccepted;

        if (player == null)
            return true;

        boolean confirmed = msg.getConfirmed();

        if (confirmed == true) {
            long timeElapsed = System.currentTimeMillis() - player.getTimeStamp("PromptRecall");
            //send fail message
            recallAccepted = timeElapsed < 15000;
        } else
            recallAccepted = false;

        if (recallAccepted == true) {
            //handle recall
            long type = player.getTimeStamp("LastRecallType");

            if (type == 1) { //recall to bind
                player.teleport(player.getBindLoc());
                player.setSafeMode();
            } else { //recall to rg
                float dist = 9999999999f;
                Building rg = null;
                Vector3fImmutable rgLoc;

                for (Runegate runegate : Runegate._runegates.values()) {

                    rgLoc = runegate.gateBuilding.getLoc();

                    float distanceSquaredToRunegate = player.getLoc().distanceSquared2D(rgLoc);

                    if (distanceSquaredToRunegate < sqr(dist))
                        rg = runegate.gateBuilding;

                }

                //nearest runegate found. teleport characterTarget

                if (rg != null) {
                    player.teleport(rg.getLoc());
                    player.setSafeMode();
                }
            }
        }

        return true;
    }

}