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

package engine.mobileAI;

import engine.Enum;
import engine.Enum.DispatchChannel;
import engine.InterestManagement.WorldGrid;
import engine.gameManager.*;
import engine.math.Vector3f;
import engine.math.Vector3fImmutable;
import engine.mobileAI.Threads.MobAIThread;
import engine.mobileAI.utilities.CombatUtilities;
import engine.mobileAI.utilities.MovementUtilities;
import engine.net.DispatchMessage;
import engine.net.client.msg.PowerProjectileMsg;
import engine.net.client.msg.UpdateStateMsg;
import engine.objects.*;
import engine.powers.PowersBase;
import engine.server.MBServerStatics;
import org.pmw.tinylog.Logger;

import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;

import static engine.math.FastMath.sqr;

public class MobAI {


    private static void AttackTarget(Mob mob, AbstractWorldObject target) {

        try {

            if (mob == null)
                return;

            if (target == null || !target.isAlive()) {
                mob.setCombatTarget(null);
                return;
            }
            if (target.getObjectType() == Enum.GameObjectType.PlayerCharacter){
                if(((PlayerCharacter)target).getHidden() > 0){
                    mob.setCombatTarget(null);
                    return;
                }
            }

            if (!CombatUtilities.inRangeToAttack(mob, target))
                return;

            switch (target.getObjectType()) {
                case PlayerCharacter:
                    PlayerCharacter targetPlayer = (PlayerCharacter) target;
                    AttackPlayer(mob, targetPlayer);
                    break;
                case Building:
                    Building targetBuilding = (Building) target;
                    AttackBuilding(mob, targetBuilding);
                    break;
                case Mob:
                    Mob targetMob = (Mob) target;
                    AttackMob(mob, targetMob);
                    break;
            }

        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: AttackTarget" + " " + e.getMessage());
        }
    }

    public static void AttackPlayer(Mob mob, PlayerCharacter target) {

        try {

            if (!mob.canSee(target)) {
                mob.setCombatTarget(null);
                return;
            }

            if (mob.behaviourType.callsForHelp)
                MobCallForHelp(mob);

            if (!MovementUtilities.inRangeDropAggro(mob, target)) {
                mob.setCombatTarget(null);
                return;
            }

            if (CombatUtilities.inRange2D(mob, target, mob.getRange())) {

                //no weapons, default mob attack speed 3 seconds.

                if (System.currentTimeMillis() < mob.getLastAttackTime())
                    return;

                // ranged mobs cant attack while running. skip until they finally stop.

                if (mob.isMoving() && mob.getRange() > 20)
                    return;

                // add timer for last attack.

                ItemBase mainHand = mob.getWeaponItemBase(true);
                ItemBase offHand = mob.getWeaponItemBase(false);

                if (mainHand == null && offHand == null) {
                    CombatUtilities.combatCycle(mob, target, true, null);
                    int delay = 3000;
                    if (mob.isSiege())
                        delay = 11000;
                    mob.setLastAttackTime(System.currentTimeMillis() + delay);
                } else if (mob.getWeaponItemBase(true) != null) {
                    int delay = 3000;
                    if (mob.isSiege())
                        delay = 11000;
                    CombatUtilities.combatCycle(mob, target, true, mob.getWeaponItemBase(true));
                    mob.setLastAttackTime(System.currentTimeMillis() + delay);
                } else if (mob.getWeaponItemBase(false) != null) {
                    int attackDelay = 3000;
                    if (mob.isSiege())
                        attackDelay = 11000;
                    CombatUtilities.combatCycle(mob, target, false, mob.getWeaponItemBase(false));
                    mob.setLastAttackTime(System.currentTimeMillis() + attackDelay);
                }
            }

            if (target.getPet() != null)
                if (target.getPet().getCombatTarget() == null && target.getPet().assist)
                    target.getPet().setCombatTarget(mob);

        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: AttackPlayer" + " " + e.getMessage());
        }

    }

    public static void AttackBuilding(Mob mob, Building target) {

        try {
            if(target == null){
                return;
            }
            if (target.getRank() == -1 || !target.isVulnerable() || BuildingManager.getBuildingFromCache(target.getObjectUUID()) == null) {
                mob.setCombatTarget(null);
                return;
            }

            City playercity = ZoneManager.getCityAtLocation(mob.getLoc());

            if (playercity != null)
                for (Mob guard : playercity.getParent().zoneMobSet)
                    if (guard.behaviourType != null && guard.behaviourType.equals(Enum.MobBehaviourType.GuardCaptain))
                        if (guard.getCombatTarget() == null && !guard.getGuild().equals(mob.getGuild()))
                            guard.setCombatTarget(mob);

            if (mob.isSiege())
                MovementManager.sendRWSSMsg(mob);

            ItemBase mainHand = mob.getWeaponItemBase(true);
            ItemBase offHand = mob.getWeaponItemBase(false);

            if (mainHand == null && offHand == null) {
                CombatUtilities.combatCycle(mob, target, true, null);
                int delay = 3000;
                if (mob.isSiege())
                    delay = 15000;
                mob.setLastAttackTime(System.currentTimeMillis() + delay);
            } else if (mob.getWeaponItemBase(true) != null) {
                int attackDelay = 3000;
                if (mob.isSiege())
                    attackDelay = 15000;
                CombatUtilities.combatCycle(mob, target, true, mob.getWeaponItemBase(true));
                mob.setLastAttackTime(System.currentTimeMillis() + attackDelay);
            } else if (mob.getWeaponItemBase(false) != null) {
                int attackDelay = 3000;
                if (mob.isSiege())
                    attackDelay = 15000;
                CombatUtilities.combatCycle(mob, target, false, mob.getWeaponItemBase(false));
                mob.setLastAttackTime(System.currentTimeMillis() + attackDelay);
            }

            if (mob.isSiege()) {
                PowerProjectileMsg ppm = new PowerProjectileMsg(mob, target);
                ppm.setRange(50);
                DispatchMessage.dispatchMsgToInterestArea(mob, ppm, DispatchChannel.SECONDARY, MBServerStatics.CHARACTER_LOAD_RANGE, false, false);
            }

        } catch (Exception e) {
            mob.setCombatTarget(null);
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: AttackBuilding" + " " + e.getMessage());
        }
    }

    public static void AttackMob(Mob mob, Mob target) {

        try {

            if (mob.getRange() >= 30 && mob.isMoving())
                return;

            //no weapons, default mob attack speed 3 seconds.

            ItemBase mainHand = mob.getWeaponItemBase(true);
            ItemBase offHand = mob.getWeaponItemBase(false);

            if (mainHand == null && offHand == null) {
                CombatUtilities.combatCycle(mob, target, true, null);
                int delay = 3000;
                if (mob.isSiege())
                    delay = 11000;
                mob.setLastAttackTime(System.currentTimeMillis() + delay);
            } else if (mob.getWeaponItemBase(true) != null) {
                int attackDelay = 3000;
                if (mob.isSiege())
                    attackDelay = 11000;
                CombatUtilities.combatCycle(mob, target, true, mob.getWeaponItemBase(true));
                mob.setLastAttackTime(System.currentTimeMillis() + attackDelay);
            } else if (mob.getWeaponItemBase(false) != null) {
                int attackDelay = 3000;
                if (mob.isSiege())
                    attackDelay = 11000;
                CombatUtilities.combatCycle(mob, target, false, mob.getWeaponItemBase(false));
                mob.setLastAttackTime(System.currentTimeMillis() + attackDelay);
                if (target.getCombatTarget() == null) {
                    target.setCombatTarget(mob);
                }
            }
            if(target.isAlive())
                target.setCombatTarget(mob);

            if(target.isPet() && !target.isAlive() && target.guardCaptain.isAlive()){
                mob.setCombatTarget(target.guardCaptain);
            }
            if(mob.isPet()){
                AttackMob(target,mob);
            }
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: AttackMob" + " " + e.getMessage());
        }
    }

    private static void Patrol(Mob mob) {

        try {

            //make sure mob is out of combat stance

            int patrolDelay = ThreadLocalRandom.current().nextInt((int) (MobAIThread.AI_PATROL_DIVISOR * 0.5f), MobAIThread.AI_PATROL_DIVISOR) + MobAIThread.AI_PATROL_DIVISOR;

            //early exit while waiting to patrol again

            if (mob.stopPatrolTime + (patrolDelay * 1000L) > System.currentTimeMillis())
                return;

            //guard captains inherit barracks patrol points dynamically

            if (mob.behaviourType.equals(Enum.MobBehaviourType.GuardCaptain)) {

                Building barracks = mob.building;

                if (barracks != null && barracks.patrolPoints != null && !barracks.getPatrolPoints().isEmpty()) {
                    mob.patrolPoints = barracks.patrolPoints;
                } else {
                    randomGuardPatrolPoint(mob);
                    return;
                }
            }

            if (mob.lastPatrolPointIndex > mob.patrolPoints.size() - 1)
                mob.lastPatrolPointIndex = 0;

            mob.destination = mob.patrolPoints.get(mob.lastPatrolPointIndex);
            mob.lastPatrolPointIndex += 1;

            MovementUtilities.aiMove(mob, mob.destination, true);

            if (mob.behaviourType.equals(Enum.MobBehaviourType.GuardCaptain))
                for (Entry<Mob, Integer> minion : mob.siegeMinionMap.entrySet())

                    //make sure mob is out of combat stance

                    if (!minion.getKey().despawned) {
                        if (MovementUtilities.canMove(minion.getKey())) {
                            Vector3f minionOffset = Formation.getOffset(2, minion.getValue() + 3);
                            minion.getKey().updateLocation();
                            Vector3fImmutable formationPatrolPoint = new Vector3fImmutable(mob.destination.x + minionOffset.x, mob.destination.y, mob.destination.z + minionOffset.z);
                            MovementUtilities.aiMove(minion.getKey(), formationPatrolPoint, true);
                        }
                    }
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: AttackTarget" + " " + e.getMessage());
        }
    }

    public static void MobCallForHelp(Mob mob) {

        try {

            boolean callGotResponse = false;

            if (mob.nextCallForHelp == 0)
                mob.nextCallForHelp = System.currentTimeMillis();

            if (mob.nextCallForHelp < System.currentTimeMillis())
                return;

            //mob sends call for help message

            ChatManager.chatSayInfo(null, mob.getName() + " calls for help!");

            Zone mobCamp = mob.getParentZone();

            for (Mob helper : mobCamp.zoneMobSet) {
                if (helper.behaviourType.respondsToCallForHelp && helper.behaviourType.BehaviourHelperType.equals(mob.behaviourType)) {
                    helper.setCombatTarget(mob.getCombatTarget());
                    callGotResponse = true;
                }
            }

            //wait 60 seconds to call for help again

            if (callGotResponse)
                mob.nextCallForHelp = System.currentTimeMillis() + 60000;

        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: MobCallForHelp" + " " + e.getMessage());
        }
    }

    public static void DetermineAction(Mob mob) {

        try {

            //always check the respawn que, respawn 1 mob max per second to not flood the client

            if (mob == null)
                return;

            if (!mob.getTimestamps().containsKey("lastExecution"))
                mob.getTimestamps().put("lastExecution", System.currentTimeMillis());

            if (System.currentTimeMillis() < mob.getTimeStamp("lastExecution"))
                return;

            mob.getTimestamps().put("lastExecution", System.currentTimeMillis() + MobAIThread.AI_PULSE_MOB_THRESHOLD);

            //trebuchet spawn handler

            if (mob.despawned && mob.getMobBase().getLoadID() == 13171) {
                CheckForRespawn(mob);
                return;
            }

            //override for guards

            if (mob.despawned && mob.isPlayerGuard) {

                if (mob.behaviourType.equals(Enum.MobBehaviourType.GuardMinion)) {
                    if (!mob.guardCaptain.isAlive() || ((Mob) mob.guardCaptain).despawned) {

                        //minions don't respawn while guard captain is dead

                        if (!mob.isAlive()) {
                            mob.deathTime = System.currentTimeMillis();
                            return;
                        }

                    }
                }

                CheckForRespawn(mob);

                //check to send mob home for player guards to prevent exploit of dragging guards away and then teleporting

                if (!mob.behaviourType.equals(Enum.MobBehaviourType.Pet1))
                    CheckToSendMobHome(mob);

                return;
            }

            //no need to continue if mob is dead, check for respawn and move on

            if (!mob.isAlive()) {
                CheckForRespawn(mob);
                return;
            }

            //no players loaded, no need to proceed
            if (mob.playerAgroMap.isEmpty()) {
                return;
            }

            if (!mob.behaviourType.equals(Enum.MobBehaviourType.Pet1))
                CheckToSendMobHome(mob);

            if (mob.getCombatTarget() != null) {

                if (!mob.getCombatTarget().isAlive()) {
                    mob.setCombatTarget(null);
                    return;
                }

                if (mob.getCombatTarget().getObjectTypeMask() == MBServerStatics.MASK_PLAYER) {

                    PlayerCharacter target = (PlayerCharacter) mob.getCombatTarget();

                    if (!mob.playerAgroMap.containsKey(target.getObjectUUID())) {
                        mob.setCombatTarget(null);
                        return;
                    }

                    if (!mob.canSee((PlayerCharacter) mob.getCombatTarget())) {
                        mob.setCombatTarget(null);
                        return;
                    }

                }
            }
            if (mob.isMoving()) {
                mob.updateLocation();
            }

            if(!mob.isPet()) {
                boolean combatState = mob.isCombat();
                mob.setCombat(mob.combatTarget != null);
                if (combatState != mob.isCombat()) {
                    //send message to update combat state
                    UpdateStateMsg rwss = new UpdateStateMsg();
                    rwss.setPlayer(mob);
                    DispatchMessage.sendToAllInRange(mob, rwss);
                }

                boolean walking = mob.isWalk();
                mob.setWalkMode(mob.combatTarget == null);
                if (walking != mob.isWalk()) {
                    //send message to update run/walk state
                    MovementManager.sendRWSSMsg(mob);
                }
            }else {
                boolean walking = mob.isWalk();
                mob.setWalkMode(mob.guardCaptain.isWalk());
                if (walking != mob.isWalk()) {
                    //send message to update run/walk state
                    MovementManager.sendRWSSMsg(mob);
                }
            }
            switch (mob.behaviourType) {
                case GuardCaptain:
                    GuardCaptainLogic(mob);
                    break;
                case GuardMinion:
                    GuardMinionLogic(mob);
                    break;
                case GuardWallArcher:
                    GuardWallArcherLogic(mob);
                    break;
                case Pet1:
                case SiegeEngine:
                    PetLogic(mob);
                    break;
                case HamletGuard:
                    HamletGuardLogic(mob);
                    break;
                default:
                    DefaultLogic(mob);
                    break;
            }
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: DetermineAction" + " " + e.getMessage());
        }
    }

    private static void CheckForAggro(Mob aiAgent, boolean pets) {

        try {

            //looks for and sets mobs combatTarget

            if (!aiAgent.isAlive())
                return;

            if(!pets) {
                ConcurrentHashMap<Integer, Float> loadedPlayers = aiAgent.playerAgroMap;
                for (Integer playerEntry : loadedPlayers.keySet()) {

                    PlayerCharacter loadedPlayer = PlayerCharacter.getFromCache(playerEntry);
                    //Player is null, let's remove them from the list.
                    if (loadedPlayer == null) {
                        loadedPlayers.remove(playerEntry);
                        continue;
                    }
                    //Player is Dead, Mob no longer needs to attempt to aggro. Remove them from aggro map.
                    if (!loadedPlayer.isAlive() || loadedPlayer.getHidden() > 0) {
                        loadedPlayers.remove(playerEntry);
                        continue;
                    }

                    //Can't see target, skip aggro.
                    if (!aiAgent.canSee(loadedPlayer))
                        continue;

                    // No aggro for this race type
                    if (aiAgent.notEnemy.size() > 0 && aiAgent.notEnemy.contains(loadedPlayer.getRace().getRaceType().getMonsterType()))
                        continue;

                    //mob has enemies and this player race is not it

                    if (aiAgent.enemy.size() > 0 && !aiAgent.enemy.contains(loadedPlayer.getRace().getRaceType().getMonsterType()))
                        continue;

                    if (MovementUtilities.inRangeToAggro(aiAgent, loadedPlayer)) {
                        aiAgent.setCombatTarget(loadedPlayer);
                        return;
                    }

                }
            } else{

                //look for pets to aggro if no players found to aggro

                HashSet<AbstractWorldObject> awoList = WorldGrid.getObjectsInRangePartial(aiAgent, MobAIThread.AI_BASE_AGGRO_RANGE, MBServerStatics.MASK_MOB);

                for (AbstractWorldObject awoMob : awoList) {

                    // exclude self.

                    if (aiAgent.equals(awoMob))
                        continue;

                    if(!((Mob)awoMob).isPet())
                        continue;

                    Mob aggroMob = (Mob) awoMob;
                    aiAgent.setCombatTarget(aggroMob);
                    return;
                }
            }
        } catch (Exception e) {
            Logger.info(aiAgent.getObjectUUID() + " " + aiAgent.getName() + " Failed At: CheckForAggro" + " " + e.getMessage());
        }
    }

    private static void CheckMobMovement(Mob mob) {
        if(mob != null && (mob.getMobBaseID() == 14220 || mob.getMobBaseID() == 14221))
            return;

        try {
            if(mob == null)
                return;

            if (!MovementUtilities.canMove(mob))
                return;

            switch (mob.behaviourType) {

                case Pet1:


                    if (mob.guardCaptain == null)
                        return;


                    if (!mob.playerAgroMap.containsKey(mob.guardCaptain.getObjectUUID())) {

                        //mob no longer has its owner loaded, translocate pet to owner


                        MovementManager.translocate(mob, mob.guardCaptain.getLoc(), null);
                        return;
                    }
                    if (mob.getCombatTarget() == null) {

                        //move back to owner


                        if (CombatUtilities.inRange2D(mob, mob.guardCaptain, 6))
                            return;


                        mob.destination = mob.guardCaptain.getLoc();
                        MovementUtilities.moveToLocation(mob, mob.destination, 5);
                    } else
                        chaseTarget(mob);
                    break;
                case GuardMinion:
                    if (!mob.guardCaptain.isAlive() || ((Mob) mob.guardCaptain).despawned)
                        randomGuardPatrolPoint(mob);
                    else {
                        if (mob.getCombatTarget() != null) {
                            chaseTarget(mob);
                        }
                    }
                    break;
                default:
                    if (mob.getCombatTarget() == null) {
                        if (!mob.isMoving())
                            Patrol(mob);
                        else {
                            mob.stopPatrolTime = System.currentTimeMillis();
                        }
                    } else {
                        chaseTarget(mob);
                    }
                    break;
            }
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: CheckMobMovement" + " " + e.getMessage());
        }
    }

    private static void CheckForRespawn(Mob aiAgent) {

        try {
            if (aiAgent.deathTime == 0) {
                aiAgent.setDeathTime(System.currentTimeMillis());
                return;
            }

            //handles checking for respawn of dead mobs even when no players have mob loaded
            //Despawn Timer with Loot currently in inventory.

            if (!aiAgent.despawned) {

                if (aiAgent.getCharItemManager().getInventoryCount() > 0) {
                    if (System.currentTimeMillis() > aiAgent.deathTime + MBServerStatics.DESPAWN_TIMER_WITH_LOOT) {
                        aiAgent.despawn();
                        aiAgent.deathTime = System.currentTimeMillis();
                    }
                    //No items in inventory.
                } else {
                    //Mob's Loot has been looted.
                    if (aiAgent.isHasLoot()) {
                        if (System.currentTimeMillis() > aiAgent.deathTime + MBServerStatics.DESPAWN_TIMER_ONCE_LOOTED) {
                            aiAgent.despawn();
                            aiAgent.deathTime = System.currentTimeMillis();
                        }
                        //Mob never had Loot.
                    } else {
                        if (System.currentTimeMillis() > aiAgent.deathTime + MBServerStatics.DESPAWN_TIMER) {
                            aiAgent.despawn();
                            aiAgent.deathTime = System.currentTimeMillis();
                        }
                    }
                }
            } else if (System.currentTimeMillis() > (aiAgent.deathTime + (aiAgent.spawnTime * 1000L))) {

                if (!Zone.respawnQue.contains(aiAgent) && !Mob.disciplineDroppers.contains(aiAgent)){
                    Zone.respawnQue.add(aiAgent);
                }
            }
        } catch (Exception e) {
            Logger.info(aiAgent.getObjectUUID() + " " + aiAgent.getName() + " Failed At: CheckForRespawn" + " " + e.getMessage());
        }
    }

    public static void CheckForAttack(Mob mob) {
        try {

            //checks if mob can attack based on attack timer and range

            if (!mob.isAlive())
                return;

            if (mob.getCombatTarget() == null)
                return;

            if (mob.getCombatTarget().getObjectType().equals(Enum.GameObjectType.PlayerCharacter) && !MovementUtilities.inRangeDropAggro(mob, (PlayerCharacter) mob.getCombatTarget()) &&
                    !mob.behaviourType.equals(Enum.MobBehaviourType.Pet1)) {

                mob.setCombatTarget(null);
                return;
            }
            if (System.currentTimeMillis() > mob.getLastAttackTime())
                AttackTarget(mob, mob.getCombatTarget());

        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: CheckForAttack" + " " + e.getMessage());
        }
    }

    private static void CheckToSendMobHome(Mob mob) {

        try {
            if (mob.behaviourType.isAgressive) {

                if (mob.isPlayerGuard()) {
                    if (mob.behaviourType.equals(Enum.MobBehaviourType.GuardCaptain))
                        CheckForPlayerGuardAggro(mob);
                } else {
                    CheckForAggro(mob,false);
                }
            }

            if (mob.isPlayerGuard() && !mob.despawned) {

                City current = ZoneManager.getCityAtLocation(mob.getLoc());

                if (current == null || !current.equals(mob.getGuild().getOwnedCity())) {

                    PowersBase recall = PowersManager.getPowerByToken(-1994153779);
                    PowersManager.useMobPower(mob, mob, recall, 40);
                    mob.setCombatTarget(null);

                    if (mob.behaviourType.equals(Enum.MobBehaviourType.GuardCaptain) && mob.isAlive()) {

                        //guard captain pulls his minions home with him

                        for (Entry<Mob, Integer> minion : mob.siegeMinionMap.entrySet()) {
                            PowersManager.useMobPower(minion.getKey(), minion.getKey(), recall, 40);
                            minion.getKey().setCombatTarget(null);
                        }
                    }
                }
            } else if (!MovementUtilities.inRangeOfBindLocation(mob)) {

                PowersBase recall = PowersManager.getPowerByToken(-1994153779);
                PowersManager.useMobPower(mob, mob, recall, 40);
                mob.setCombatTarget(null);

                mob.playerAgroMap.replaceAll((e, v) -> 0f);
            }
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: CheckToSendMobHome" + " " + e.getMessage());
        }
    }

    private static void chaseTarget(Mob mob) {

        try {
            if (mob.combatTarget.getObjectType() == Enum.GameObjectType.PlayerCharacter){
                if(((PlayerCharacter)mob.combatTarget).getHidden() > 0){
                    mob.setCombatTarget(null);
                    return;
                }
            }
            float range = mob.getRange();
            if(range < 6)
                range = 6;
            float rangeSquared = range * range;
            float distanceSquared = mob.getLoc().distanceSquared2D(mob.getCombatTarget().getLoc());

            if(mob.isMoving() && distanceSquared < rangeSquared - 50) {
                mob.destination = mob.getLoc();
                MovementUtilities.moveToLocation(mob, mob.destination, 0);
            } else if (!CombatUtilities.inRange2D(mob, mob.getCombatTarget(), mob.getRange())) {
                if (mob.getRange() > 15) {
                    mob.destination = mob.getCombatTarget().getLoc();
                    MovementUtilities.moveToLocation(mob, mob.destination, 0);
                } else {

                    //check if building

                    switch (mob.getCombatTarget().getObjectType()) {
                        case PlayerCharacter:
                        case Mob:
                            mob.destination = MovementUtilities.GetDestinationToCharacter(mob, (AbstractCharacter) mob.getCombatTarget());
                            MovementUtilities.moveToLocation(mob, mob.destination, mob.getRange() + 1);
                            break;
                        case Building:
                            mob.destination = mob.getCombatTarget().getLoc();
                            MovementUtilities.moveToLocation(mob, mob.getCombatTarget().getLoc(), 0);
                            break;
                    }
                }
            }
            mob.updateMovementState();
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: chaseTarget" + " " + e.getMessage());
        }
    }

    private static void SafeGuardAggro(Mob mob) {
        try {

            HashSet<AbstractWorldObject> awoList = WorldGrid.getObjectsInRangePartial(mob, 100, MBServerStatics.MASK_MOB);

            for (AbstractWorldObject awoMob : awoList) {

                //dont scan self.

                if (mob.equals(awoMob) || (mob.agentType.equals(Enum.AIAgentType.GUARD)) || awoMob.getObjectType().equals(Enum.GameObjectType.PlayerCharacter))
                    continue;

                Mob aggroMob = (Mob) awoMob;

                //don't attack other guards

                if ((aggroMob.agentType.equals(Enum.AIAgentType.GUARD)))
                    continue;

                if (aggroMob.behaviourType.equals(Enum.MobBehaviourType.Pet1))
                    continue;

                if (mob.getLoc().distanceSquared2D(aggroMob.getLoc()) > sqr(50))
                    continue;

                mob.setCombatTarget(aggroMob);
            }
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: SafeGuardAggro" + " " + e.getMessage());
        }
    }

    public static void GuardCaptainLogic(Mob mob) {

        try {
            if (mob.getCombatTarget() == null)
                CheckForPlayerGuardAggro(mob);

            CheckMobMovement(mob);
            CheckForAttack(mob);
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: GuardCaptainLogic" + " " + e.getMessage());
        }
    }

    public static void GuardMinionLogic(Mob mob) {

        try {
            if (!mob.guardCaptain.isAlive()) {

                if (mob.getCombatTarget() == null) {
                    CheckForPlayerGuardAggro(mob);
                }
            }else {
                if (mob.guardCaptain.getCombatTarget() != null)
                    mob.setCombatTarget(mob.guardCaptain.getCombatTarget());
                else if (mob.getCombatTarget() != null)
                    mob.setCombatTarget(null);
            }
            CheckMobMovement(mob);
            CheckForAttack(mob);
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: GuardMinionLogic" + " " + e.getMessage());
        }
    }

    public static void GuardWallArcherLogic(Mob mob) {

        try {
            if (mob.getCombatTarget() == null)
                CheckForPlayerGuardAggro(mob);
            else
                CheckForAttack(mob);
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: GuardWallArcherLogic" + " " + e.getMessage());
        }
    }

    private static void PetLogic(Mob mob) {

        try {


            if (mob.guardCaptain == null && !mob.isNecroPet() && !mob.isSiege())
                if (ZoneManager.getSeaFloor().zoneMobSet.contains(mob))
                    mob.killCharacter("no owner");

            if (MovementUtilities.canMove(mob) && mob.behaviourType.canRoam)
                CheckMobMovement(mob);

            CheckForAttack(mob);

            //recover health

            if (!mob.getTimestamps().containsKey("HEALTHRECOVERED"))
                mob.getTimestamps().put("HEALTHRECOVERED", System.currentTimeMillis());

            if (mob.isSit() && mob.getTimeStamp("HEALTHRECOVERED") < System.currentTimeMillis() + 3000)
                if (mob.getHealth() < mob.getHealthMax()) {

                    float recoveredHealth = mob.getHealthMax() * ((1 + mob.getBonuses().getFloatPercentAll(Enum.ModType.HealthRecoverRate, Enum.SourceType.None)) * 0.01f);
                    mob.setHealth(mob.getHealth() + recoveredHealth);
                    mob.getTimestamps().put("HEALTHRECOVERED", System.currentTimeMillis());

                    if (mob.getHealth() > mob.getHealthMax())
                        mob.setHealth(mob.getHealthMax());
                }
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: PetLogic" + " " + e.getMessage());
        }
    }

    private static void HamletGuardLogic(Mob mob) {

        try {
            //safehold guard

            if (mob.getCombatTarget() == null)
                SafeGuardAggro(mob);
            else if (!mob.getCombatTarget().isAlive())
                SafeGuardAggro(mob);

            CheckForAttack(mob);
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: HamletGuardLogic" + " " + e.getMessage());
        }
    }

    private static void DefaultLogic(Mob mob) {

        try {

            if(mob.combatTarget != null && mob.combatTarget.getObjectType().equals(Enum.GameObjectType.PlayerCharacter)){
                PlayerCharacter tar = (PlayerCharacter)mob.combatTarget;
                if (!mob.canSee(tar)) {
                    mob.setCombatTarget(null);
                }
            }

            if (mob.behaviourType.isAgressive) {
                if (mob.getCombatTarget() == null) {
                    if (mob.behaviourType == Enum.MobBehaviourType.HamletGuard) {
                        SafeGuardAggro(mob);  //safehold guard
                    } else {
                        CheckForAggro(mob, false);   //normal aggro
                        if (mob.combatTarget == null)
                            CheckForAggro(mob, true); // look for pets if no players to aggro
                    }
                }
            }

            //check if mob can move for patrol or moving to target

            if (mob.behaviourType.canRoam)
                CheckMobMovement(mob);

            //check if mob can attack if it isn't wimpy

            if (!mob.behaviourType.isWimpy && mob.getCombatTarget() != null)
                CheckForAttack(mob);

        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: DefaultLogic" + " " + e.getMessage());
        }
    }

    public static void CheckForPlayerGuardAggro(Mob mob) {

        try {

            //looks for and sets mobs combatTarget

            if (!mob.isAlive())
                return;

            ConcurrentHashMap<Integer, Float> loadedPlayers = mob.playerAgroMap;

            for (Integer playerEntry : loadedPlayers.keySet()) {

                PlayerCharacter loadedPlayer = PlayerCharacter.getFromCache(playerEntry);

                //Player is null, let's remove them from the list.

                if (loadedPlayer == null) {
                    loadedPlayers.remove(playerEntry);
                    continue;
                }

                //Player is Dead, Mob no longer needs to attempt to aggro. Remove them from aggro map.

                if (!loadedPlayer.isAlive()) {
                    loadedPlayers.remove(playerEntry);
                    continue;
                }

                //Can't see target, skip aggro.

                if (!mob.canSee(loadedPlayer))
                    continue;

                // No aggro for this player

                if (!GuardCanAggro(mob, loadedPlayer))
                    continue;

                if (MovementUtilities.inRangeToAggro(mob, loadedPlayer) && mob.getCombatTarget() == null) {
                    mob.setCombatTarget(loadedPlayer);
                    return;
                }
            }
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: CheckForPlayerGuardAggro" + e.getMessage());
        }
    }

    public static Boolean GuardCanAggro(Mob mob, PlayerCharacter target) {

        try {

            if (mob.getGuild().getNation().equals(target.getGuild().getNation()))
                return false;

            if (mob.behaviourType.equals(Enum.MobBehaviourType.GuardMinion)) {
                if (Objects.requireNonNull(mob.guardCaptain.building.getCity()).cityOutlaws.contains(target.getObjectUUID())) {
                    return true;
                }
            } else if (Objects.requireNonNull(mob.building.getCity()).cityOutlaws.contains(target.getObjectUUID())) {
                return true;
            }

            //first check condemn list for aggro allowed (allies button is checked)

            if (Objects.requireNonNull(ZoneManager.getCityAtLocation(mob.getLoc())).getTOL().reverseKOS) {
                for (Entry<Integer, Condemned> entry : Objects.requireNonNull(ZoneManager.getCityAtLocation(mob.getLoc())).getTOL().getCondemned().entrySet()) {

                    //target is listed individually

                    if (entry.getValue().getPlayerUID() == target.getObjectUUID() && entry.getValue().isActive())
                        return false;

                    //target's guild is listed

                    if (Guild.getGuild(entry.getValue().getGuildUID()) == target.getGuild())
                        return false;

                    //target's nation is listed

                    if (Guild.getGuild(entry.getValue().getGuildUID()) == target.getGuild().getNation())
                        return false;
                }
                return true;
            } else {

                //allies button is not checked

                for (Entry<Integer, Condemned> entry : Objects.requireNonNull(ZoneManager.getCityAtLocation(mob.getLoc())).getTOL().getCondemned().entrySet()) {

                    //target is listed individually

                    if (entry.getValue().getPlayerUID() == target.getObjectUUID() && entry.getValue().isActive())
                        return true;

                    //target's guild is listed

                    if (Guild.getGuild(entry.getValue().getGuildUID()) == target.getGuild())
                        return true;

                    //target's nation is listed

                    if (Guild.getGuild(entry.getValue().getGuildUID()) == target.getGuild().getNation())
                        return true;
                }
            }
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: GuardCanAggro" + " " + e.getMessage());
        }
        return false;
    }

    public static void randomGuardPatrolPoint(Mob mob) {

        try {

            //early exit for a mob who is already moving to a patrol point
            //while mob moving, update lastPatrolTime so that when they stop moving the 10 second timer can begin

            if (mob.isMoving()) {
                mob.stopPatrolTime = System.currentTimeMillis();
                return;
            }

            //wait between 10 and 15 seconds after reaching patrol point before moving

            int patrolDelay = ThreadLocalRandom.current().nextInt(10000) + 5000;

            //early exit while waiting to patrol again

            if (mob.stopPatrolTime + patrolDelay > System.currentTimeMillis())
                return;

            float xPoint = ThreadLocalRandom.current().nextInt(400) - 200;
            float zPoint = ThreadLocalRandom.current().nextInt(400) - 200;
            Vector3fImmutable TreePos = mob.getGuild().getOwnedCity().getLoc();
            mob.destination = new Vector3fImmutable(TreePos.x + xPoint, TreePos.y, TreePos.z + zPoint);

            MovementUtilities.aiMove(mob, mob.destination, true);

            if (mob.behaviourType.equals(Enum.MobBehaviourType.GuardCaptain)) {
                for (Entry<Mob, Integer> minion : mob.siegeMinionMap.entrySet()) {

                    //make sure mob is out of combat stance

                    if (!minion.getKey().despawned) {
                        if (MovementUtilities.canMove(minion.getKey())) {
                            Vector3f minionOffset = Formation.getOffset(2, minion.getValue() + 3);
                            minion.getKey().updateLocation();
                            Vector3fImmutable formationPatrolPoint = new Vector3fImmutable(mob.destination.x + minionOffset.x, mob.destination.y, mob.destination.z + minionOffset.z);
                            MovementUtilities.aiMove(minion.getKey(), formationPatrolPoint, true);
                        }
                    }
                }
            }
        } catch (Exception e) {
            Logger.info(mob.getObjectUUID() + " " + mob.getName() + " Failed At: randomGuardPatrolPoints" + " " + e.getMessage());
        }
    }
}