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


package engine.objects;

import engine.Enum;
import engine.Enum.ModType;
import engine.Enum.SourceType;
import engine.gameManager.ChatManager;
import engine.gameManager.DbManager;
import engine.powers.EffectsBase;
import engine.server.MBServerStatics;
import org.pmw.tinylog.Logger;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.concurrent.ConcurrentHashMap;

public class Resists {

    private static ConcurrentHashMap<Integer, Resists> mobResists = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW);
    private ConcurrentHashMap<SourceType, Float> resists = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW);
    private ConcurrentHashMap<SourceType, Boolean> immuneTo = new ConcurrentHashMap<>(MBServerStatics.CHM_INIT_CAP, MBServerStatics.CHM_LOAD, MBServerStatics.CHM_THREAD_LOW);
    private SourceType protection;
    private int protectionTrains = 0;
    private boolean immuneToAll;

    /**
     * Generic Constructor
     */

    public Resists(String type) {
        switch (type) {
            case "Building":
                setBuildingResists();
                break;
            case "Mine":
                setMineResists();
                break;
            default:
                setGenericResists();
                break;
        }
    }

    public Resists(Resists r) {
        for (SourceType dt : r.resists.keySet())
            this.resists.put(dt, r.resists.get(dt));
        for (SourceType dt : r.immuneTo.keySet())
            this.immuneTo.put(dt, r.immuneTo.get(dt));
        this.protection = r.protection;
        this.protectionTrains = r.protectionTrains;
        this.immuneToAll = r.immuneToAll;
    }

    /**
     * Generic Constructor for player
     */
    public Resists(PlayerCharacter pc) {
        setGenericResists();
    }

    public Resists(Mob mob) {
        setGenericResists();
    }

    /**
     * Called for mobBase when getting from the db fails
     */
    public Resists(MobBase mobBase) {
        setGenericResists();
    }

    /**
     * Database Constructor
     */
    public Resists(ResultSet rs) throws SQLException {
        this.immuneToAll = false;
        this.resists.put(SourceType.SLASHING, rs.getFloat("slash"));
        this.resists.put(SourceType.CRUSHING, rs.getFloat("crush"));
        this.resists.put(SourceType.PIERCING, rs.getFloat("pierce"));
        this.resists.put(SourceType.MAGIC, rs.getFloat("magic"));
        this.resists.put(SourceType.BLEEDING, rs.getFloat("bleed"));
        this.resists.put(SourceType.POISON, rs.getFloat("poison"));
        this.resists.put(SourceType.MENTAL, rs.getFloat("mental"));
        this.resists.put(SourceType.HOLY, rs.getFloat("holy"));
        this.resists.put(SourceType.UNHOLY, rs.getFloat("unholy"));
        this.resists.put(SourceType.LIGHTNING, rs.getFloat("lightning"));
        this.resists.put(SourceType.FIRE, rs.getFloat("fire"));
        this.resists.put(SourceType.COLD, rs.getFloat("cold"));
        this.resists.put(SourceType.HEALING, 0f);
    }

    //Handle Fortitudes
    private static float handleFortitude(AbstractCharacter target, SourceType type, float damage) {
        if (target == null || !(target.getObjectType().equals(Enum.GameObjectType.PlayerCharacter)))
            return damage;
        PlayerBonuses bonus = target.getBonuses();

        //see if there is a fortitude
        float damageCap = bonus.getFloatPercentAll(ModType.DamageCap, SourceType.NONE);
        if (damageCap == 0f || type == SourceType.HEALING)
            return damage;

        //is fortitude, Are we under the cap?
        float maxHealth = target.getHealthMax();
        float capFire = maxHealth * (damageCap);
        if (damage < capFire)
            return damage;

        //let's see if valid damagetype to apply it
        boolean exclusive;
        HashSet<SourceType> forts = bonus.getList(ModType.IgnoreDamageCap);
        if (forts == null) {
            exclusive = true;
            forts = bonus.getList(ModType.ExclusiveDamageCap);
        } else
            exclusive = false;
        if (forts == null || !isValidDamageCapType(forts, type, exclusive))
            return damage;

        float adjustedDamage = bonus.getFloatPercentAll(ModType.AdjustAboveDmgCap, SourceType.NONE);
        //Adjust damage down and return new amount
        float aadc = 1 + adjustedDamage;
        return capFire * aadc;
    }

    //Test if Damagetype is valid for foritude
    private static boolean isValidDamageCapType(HashSet<SourceType> forts, SourceType damageType, boolean exclusive) {
        for (SourceType fort : forts) {
            SourceType dt = SourceType.valueOf(fort.name().toUpperCase());

            if (dt == SourceType.NONE)
                continue;

            if (dt == damageType) {
                return exclusive;
            }
        }
        return !exclusive;
    }

    /**
     * Calculate Current Resists for Player
     */
    public static void calculateResists(AbstractCharacter ac) {
        if (ac.getResists() != null)
            ac.getResists().calculateResists(ac, true);
        else
            Logger.error("Unable to find resists for character " + ac.getObjectUUID());
    }

    private static float[] getArmorResists(Item armor, float[] phys) {

        if (armor == null)
            return phys;

        if (armor.template.item_type.equals(Enum.ItemType.ARMOR)) {
            phys[0] += armor.template.combat_attack_resist.get("SLASHING");
            phys[1] += armor.template.combat_attack_resist.get("CRUSHING");
            phys[2] += armor.template.combat_attack_resist.get("PIERCING");
        }

        return phys;
    }

    /**
     * Get mob resists from db if there, otherwise set defaults
     */
    public static Resists getResists(int resistID) {
        //check cache first
        if (mobResists.containsKey(resistID))
            return new Resists(mobResists.get(resistID));

        //get from database
        Resists resists = DbManager.ResistQueries.GET_RESISTS_FOR_MOB(resistID);
        if (resists != null) {
            mobResists.put(resistID, resists);
            return new Resists(resists);
        }

        //failed, may want to debug this
        return null;
    }

    /**
     * Create generic resists for buildings
     */
    public final void setBuildingResists() {
        this.immuneToAll = false;
        this.resists.put(SourceType.SLASHING, 85f);
        this.resists.put(SourceType.CRUSHING, 85f);
        this.immuneTo.put(SourceType.PIERCING, true);
        this.immuneTo.put(SourceType.MAGIC, true);
        this.immuneTo.put(SourceType.BLEEDING, true);
        this.immuneTo.put(SourceType.POISON, true);
        this.immuneTo.put(SourceType.MENTAL, true);
        this.immuneTo.put(SourceType.HOLY, true);
        this.immuneTo.put(SourceType.UNHOLY, true);
        this.immuneTo.put(SourceType.LIGHTNING, true);
        this.immuneTo.put(SourceType.FIRE, true);
        this.immuneTo.put(SourceType.COLD, true);
        this.resists.put(SourceType.SIEGE, 0f);

    }

    /**
     * Create generic resists for mines
     */
    public final void setMineResists() {
        this.immuneToAll = false;
        this.immuneTo.put(SourceType.SLASHING, true);
        this.immuneTo.put(SourceType.CRUSHING, true);
        this.immuneTo.put(SourceType.PIERCING, true);
        this.immuneTo.put(SourceType.MAGIC, true);
        this.immuneTo.put(SourceType.BLEEDING, true);
        this.immuneTo.put(SourceType.POISON, true);
        this.immuneTo.put(SourceType.MENTAL, true);
        this.immuneTo.put(SourceType.HOLY, true);
        this.immuneTo.put(SourceType.UNHOLY, true);
        this.immuneTo.put(SourceType.LIGHTNING, true);
        this.immuneTo.put(SourceType.FIRE, true);
        this.immuneTo.put(SourceType.COLD, true);
        this.resists.put(SourceType.SIEGE, 0f);
    }

    /**
     * Create generic resists
     */
    public final void setGenericResists() {
        this.immuneToAll = false;
        this.resists.put(SourceType.SLASHING, 0f);
        this.resists.put(SourceType.CRUSHING, 0f);
        this.resists.put(SourceType.PIERCING, 0f);
        this.resists.put(SourceType.MAGIC, 0f);
        this.resists.put(SourceType.BLEEDING, 0f);
        this.resists.put(SourceType.POISON, 0f);
        this.resists.put(SourceType.MENTAL, 0f);
        this.resists.put(SourceType.HOLY, 0f);
        this.resists.put(SourceType.UNHOLY, 0f);
        this.resists.put(SourceType.LIGHTNING, 0f);
        this.resists.put(SourceType.FIRE, 0f);
        this.resists.put(SourceType.COLD, 0f);
        this.resists.put(SourceType.HEALING, 0f);
        this.immuneTo.put(SourceType.SIEGE, true);

    }

    /**
     * Get a resist
     */
    public float getResist(SourceType type, int trains) {
        //get resisted amount
        Float amount = 0f;
        if (this.resists.containsKey(type))
            amount = this.resists.get(type);

        //add protection
        if (trains > 0 && protection != null && type.equals(this.protection)) {
            float prot = 50 + this.protectionTrains - trains;
            amount += (prot >= 0) ? prot : 0;
        }

        if (amount == null)
            return 0f;
        if (amount > 75f)
            return 75f;
        return amount;
    }

    /**
     * get immuneTo
     */
    public boolean immuneTo(SourceType type) {
        if (this.immuneTo.containsKey(type))
            return this.immuneTo.get(type);
        else
            return false;
    }

    /**
     * get immuneToAll
     */
    public boolean immuneToAll() {
        return this.immuneToAll;
    }

    public boolean immuneToAttacks() {
        return immuneTo(SourceType.IMMUNETOATTACK);
    }

    /**
     * Set a resist
     */
    public void setResist(SourceType type, float value) {
        this.resists.put(type, value);
    }

    /**
     * set immuneToAll
     */
    public void setImmuneToAll(boolean value) {
        this.immuneToAll = value;
    }

    /**
     * set resists from mobbase
     */
    public void setMobResists(int resistID) {
        //TODO add this in later
        //calls `static_npc_mob_resists` table WHERE `ID`='resistID'
    }

    /**
     * get Damage after resist
     * Expects heals as negative damage and damage as positive damage for fortitudes.
     */
    public float getResistedDamage(AbstractCharacter source, AbstractCharacter target, SourceType type, float damage, int trains) {
        //handle fortitudes
        damage = handleFortitude(target, type, damage);
        //calculate armor piercing
        float ap = source.getBonuses().getFloatPercentAll(ModType.ArmorPiercing, SourceType.NONE);
        float damageAfterResists = damage * (1 - (this.getResist(type, trains) * 0.01f) + ap);
        //check to see if any damage absorbers should cancel
        if (target != null) {
            //debug damage shields if any found
            if (source.getDebug(2) && source.getObjectType().equals(Enum.GameObjectType.PlayerCharacter)) {
                Effect da = target.getDamageAbsorber();
                if (da != null && da.getEffectsBase() != null) {
                    EffectsBase eb = da.getEffectsBase();
                    String text = "Damage: " + damage + '\n';
                    text += "Damage after resists: " + damageAfterResists + '\n';
                    text += "Attack damage type: " + type.name() + '\n';
                    text += "Fortitude damage types; " + eb.getDamageTypes() + '\n';
                    text += "Fortitude damage before attack: " + da.getDamageAmount() + '\n';
                    text += "Fortitude total health: " + eb.getDamageAmount(da.getTrains()) + '\n';
                    text += "Fortitude trains: " + da.getTrains();
                    ChatManager.chatSystemInfo((PlayerCharacter) source, text);
                }
            }
            target.cancelOnTakeDamage(type, (damageAfterResists));
        }
        return damageAfterResists;
    }

    public void calculateResists(AbstractCharacter ac, boolean val) {
        this.immuneTo.clear();

        // get resists for runes
        PlayerBonuses rb = ac.getBonuses();
        float slash = 0f, crush = 0f, pierce = 0f, magic = 0f, bleed = 0f, mental = 0f, holy = 0f, unholy = 0f, poison = 0f, lightning = 0f, fire = 0f, cold = 0f, healing = 0f;

        if (rb != null) {
            // Handle immunities
            if (rb.getBool(ModType.ImmuneTo, SourceType.STUN))
                this.immuneTo.put(SourceType.STUN, true);
            if (rb.getBool(ModType.ImmuneTo, SourceType.BLIND))
                this.immuneTo.put(SourceType.BLIND, true);
            if (rb.getBool(ModType.ImmuneToAttack, SourceType.NONE))
                this.immuneTo.put(SourceType.IMMUNETOATTACK, true);
            if (rb.getBool(ModType.ImmuneToPowers, SourceType.NONE))
                this.immuneTo.put(SourceType.IMMUNETOPOWERS, true);
            if (rb.getBool(ModType.ImmuneTo, SourceType.POWERBLOCK))
                this.immuneTo.put(SourceType.POWERBLOCK, true);
            if (rb.getBool(ModType.ImmuneTo, SourceType.DEBUFF))
                this.immuneTo.put(SourceType.DEBUFF, true);
            if (rb.getBool(ModType.ImmuneTo, SourceType.FEAR))
                this.immuneTo.put(SourceType.FEAR, true);
            if (rb.getBool(ModType.ImmuneTo, SourceType.CHARM))
                this.immuneTo.put(SourceType.CHARM, true);
            if (rb.getBool(ModType.ImmuneTo, SourceType.ROOT))
                this.immuneTo.put(SourceType.ROOT, true);
            if (rb.getBool(ModType.ImmuneTo, SourceType.SNARE))
                this.immuneTo.put(SourceType.SNARE, true);

            // Handle resists
            slash += rb.getFloat(ModType.Resistance, SourceType.SLASHING);
            crush += rb.getFloat(ModType.Resistance, SourceType.CRUSHING);
            pierce += rb.getFloat(ModType.Resistance, SourceType.PIERCING);
            magic += rb.getFloat(ModType.Resistance, SourceType.MAGIC);
            bleed += rb.getFloat(ModType.Resistance, SourceType.BLEEDING);
            poison += rb.getFloat(ModType.Resistance, SourceType.POISON);
            mental += rb.getFloat(ModType.Resistance, SourceType.MENTAL);
            holy += rb.getFloat(ModType.Resistance, SourceType.HOLY);
            unholy += rb.getFloat(ModType.Resistance, SourceType.UNHOLY);
            lightning += rb.getFloat(ModType.Resistance, SourceType.LIGHTNING);
            fire += rb.getFloat(ModType.Resistance, SourceType.FIRE);
            cold += rb.getFloat(ModType.Resistance, SourceType.COLD);
            healing += rb.getFloat(ModType.Resistance, SourceType.HEALING); // DamageType.Healing.name());

        }

        // get resists from equipment
        if (ac.getObjectType().equals(Enum.GameObjectType.PlayerCharacter)) {
            if (ac.getCharItemManager() != null && ac.getCharItemManager().getEquipped() != null) {
                float[] phys = {0f, 0f, 0f};
                ConcurrentHashMap<Enum.EquipSlotType, Item> equip = ac.getCharItemManager().getEquipped();

                // get base physical resists
                phys = Resists.getArmorResists(equip.get(Enum.EquipSlotType.HELM), phys);
                phys = Resists.getArmorResists(equip.get(Enum.EquipSlotType.CHEST), phys);
                phys = Resists.getArmorResists(equip.get(Enum.EquipSlotType.UPARM), phys);
                phys = Resists.getArmorResists(equip.get(Enum.EquipSlotType.HANDS), phys);
                phys = Resists.getArmorResists(equip.get(Enum.EquipSlotType.LEGS), phys);
                phys = Resists.getArmorResists(equip.get(Enum.EquipSlotType.FEET), phys);
                slash += phys[0];
                crush += phys[1];
                pierce += phys[2];

            }
        }

        this.resists.put(SourceType.SLASHING, slash);
        this.resists.put(SourceType.CRUSHING, crush);
        this.resists.put(SourceType.PIERCING, pierce);
        this.resists.put(SourceType.MAGIC, magic);
        this.resists.put(SourceType.BLEEDING, bleed);
        this.resists.put(SourceType.POISON, poison);
        this.resists.put(SourceType.MENTAL, mental);
        this.resists.put(SourceType.HOLY, holy);
        this.resists.put(SourceType.UNHOLY, unholy);
        this.resists.put(SourceType.LIGHTNING, lightning);
        this.resists.put(SourceType.FIRE, fire);
        this.resists.put(SourceType.COLD, cold);
        this.resists.put(SourceType.HEALING, healing);
        this.immuneTo.put(SourceType.SIEGE, true);

        // debug printing of resists
        // printResists(pc);
    }

    public void printResistsToClient(PlayerCharacter pc) {
        for (SourceType dt : resists.keySet())
            ChatManager.chatSystemInfo(pc, "  resist." + dt.name() + ": " + resists.get(dt));
        for (SourceType dt : immuneTo.keySet())
            ChatManager.chatSystemInfo(pc, "  immuneTo." + dt.name() + ": " + immuneTo.get(dt));
        ChatManager.chatSystemInfo(pc, "  immuneToAll: " + this.immuneToAll);
        if (protection != null)
            ChatManager.chatSystemInfo(pc, "  Protection: " + protection.name() + ", Trains: " + protectionTrains);
        else
            ChatManager.chatSystemInfo(pc, "  Protection: None");
    }

    public String getResists(PlayerCharacter pc) {
        String out = pc.getName();

        out += "Resists: ";
        Iterator<SourceType> it = this.resists.keySet().iterator();
        while (it.hasNext()) {
            SourceType damType = it.next();
            String dtName = damType.name();
            out += dtName + '=' + this.resists.get(dtName) + ", ";
        }

        out += "ImmuneTo: ";
        it = this.immuneTo.keySet().iterator();
        while (it.hasNext()) {
            SourceType damType = it.next();

            String dtName = damType.name();
            out += dtName + '=' + this.resists.get(dtName) + ", ";
        }

        if (protection != null)
            out += "Protection: " + protection.name() + ", Trains: " + protectionTrains;
        else
            out += "Protection: none";

        return out;
    }
}
