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


package engine.net.client.handlers;

import engine.InterestManagement.WorldGrid;
import engine.exception.MsgSendException;
import engine.gameManager.ChatManager;
import engine.CollisionEngine.CollisionManager;
import engine.gameManager.MovementManager;
import engine.math.Vector3fImmutable;
import engine.net.client.ClientConnection;
import engine.net.client.msg.ClientNetMsg;
import engine.net.client.msg.MoveToPointMsg;
import engine.objects.*;
import engine.server.MBServerStatics;

import java.awt.geom.Line2D;

import java.util.HashSet;

public class MoveToPointHandler extends AbstractClientMsgHandler {

    public MoveToPointHandler() {
        super(MoveToPointMsg.class);
    }

    @Override
    protected boolean _handleNetMsg(ClientNetMsg baseMsg,
                                    ClientConnection origin) throws MsgSendException {
        MoveToPointMsg msg = (MoveToPointMsg) baseMsg;
        PlayerCharacter pc = origin.getPlayerCharacter();
        if(pc == null)
            return true;

        //check for collisions
        Line2D travelLine = new Line2D.Float();
        Vector3fImmutable endLoc = new Vector3fImmutable(msg.getEndLat(),msg.getEndAlt(),msg.getEndLon());
        travelLine.setLine(pc.loc.x,pc.loc.z,endLoc.x,endLoc.z);
        float movementDistance = 185 + pc.loc.distance(endLoc);
        HashSet<AbstractWorldObject> awoList = WorldGrid.getObjectsInRangePartial(pc.loc, movementDistance, MBServerStatics.MASK_BUILDING);
        for(AbstractWorldObject awo : awoList){
            Building building = (Building)awo;
            if(CollisionManager.CollisionDetected(building, travelLine,pc.getCharacterHeight(),pc.loc.y)){
                ChatManager.chatSystemInfo(pc, "Collision Detected");
                //msg.setEndCoord();
                MovementManager.movement(msg, pc);
                return true;
            }
        }
        ChatManager.chatSystemInfo(pc, "No Collision Detected");
        MovementManager.movement(msg, pc);
        return true;
    }
}
