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

package engine.wpak;

import engine.gameManager.ConfigManager;
import engine.mbEnums;
import engine.wpak.data.ConditionEntry;
import engine.wpak.data.Effect;
import engine.wpak.data.ModifierEntry;
import org.pmw.tinylog.Logger;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class EffectsParser {

    public static String effectsPath = ConfigManager.DEFAULT_DATA_DIR + "wpak/Effects.cfg";
    private static final Pattern EFFECT_REGEX = Pattern.compile("(?<=EFFECTBEGIN)(.+?)(?=EFFECTEND)", Pattern.DOTALL);
    private static final Pattern SOURCE_REGEX = Pattern.compile("(?<=SOURCEBEGIN)(.+?)(?=SOURCEEND)", Pattern.DOTALL);
    private static final Pattern MODS_REGEX = Pattern.compile("(?<=MODSBEGIN)(.+?)(?=MODSEND)", Pattern.DOTALL);
    private static final Pattern CONDITIONS_REGEX = Pattern.compile("(?<=CONDITIONBEGIN)(.+?)(?=CONDITIONEND)", Pattern.DOTALL);
    private static final Pattern STRSPLIT_REGEX = Pattern.compile("([^\"]\\S*|\"[^\"]*\")\\s*"); // Regex ignores spaces within quotes

    public static void parseWpakFile() {

        // Read .wpak file from disk

        byte[] fileData;

        try {
            fileData = Files.readAllBytes(Paths.get(effectsPath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String fileContents = new String(fileData);

        // Iterate over effect entries from .wpak data

        Matcher matcher = EFFECT_REGEX.matcher(fileContents);

        while (matcher.find()) {
            try {
                Effect effect = parseEffectEntry(matcher.group());
                // WpakPowerManager._effectsLookup.put(effect.effect_id, effect);
            } catch (Exception e) {
                Logger.error("EFFECT PARSE FAILED: " + e);
            }
        }
    }

    private static Effect parseEffectEntry(String effectData) {

        Effect effect = new Effect();

        // Parse fields that lie outside the other tags

        effect.isItemEffect = effectData.contains("IsItemEffect");
        effect.isSpireEffect = effectData.contains("IsSpireEffect");
        effect.ignoreNoMod = effectData.contains("IgnoreNoMod");
        effect.dontSave = effectData.contains("DontSave");

        // Remove all lines that contain a # and leading/trailing blank lines

        effectData = effectData.replaceAll("(?m)^(\\s*#.*|\\s*)\r?\n?", "");
        effectData = effectData.trim();

        // Parse effect entry header

        String firstLine;
        ArrayList<String> effectHeader = new ArrayList<>();

        // Some effects exist without sources/mods or conditions
        // (ACID "MOB" 0)

        if (effectData.indexOf('\n') > 0)
            firstLine = effectData.substring(0, effectData.indexOf('\n'));
        else
            firstLine = effectData;

        Matcher matcher = STRSPLIT_REGEX.matcher(firstLine);

        while (matcher.find())
            effectHeader.add(matcher.group().trim());

        effect.effect_id = effectHeader.get(0);
        effect.effect_name = effectHeader.get(1);
        effect.effect_name = effect.effect_name.replaceAll("\"", "");

        // Some effect mods have no icon
        // (SEEINVIS-SHADE "See Invis")

        if (effectHeader.size() == 3)
            effect.icon = Integer.parseInt(effectHeader.get(2));
        else
            effect.icon = 0;

        // Parse source entries

        matcher = SOURCE_REGEX.matcher(effectData);

        while (matcher.find())
            effect.sources.add(matcher.group().trim());

        // Parse modifier entries

        matcher = MODS_REGEX.matcher(effectData);

        // Iterate effect entries from .wpak config data

        while (matcher.find()) {
            ModifierEntry modifierEntry = parseModEntry(matcher.group());
            effect.mods.add(modifierEntry);
        }

        // Parse Conditions

        matcher = CONDITIONS_REGEX.matcher(effectData);

        while (matcher.find()) {
            String[] conditions = matcher.group().trim().split("\n");

            for (String condition : conditions) {
                List<String> parameters = Arrays.asList(condition.trim().split("\\s+"));
                Iterator<String> iterator = parameters.iterator();

                ConditionEntry conditionEntry = new ConditionEntry();
                conditionEntry.condition = iterator.next();
                conditionEntry.arg = Integer.parseInt(iterator.next());

                if (iterator.hasNext())
                    conditionEntry.curveType = mbEnums.CompoundCurveType.valueOf(iterator.next());

                while (iterator.hasNext())
                    conditionEntry.damageTypes.add(mbEnums.DamageType.valueOf(iterator.next().toUpperCase()));

                effect.conditions.add(conditionEntry);
            }
        }

        return effect;
    }

    private static ModifierEntry parseModEntry(String modData) {

        ModifierEntry modifierEntry = new ModifierEntry();

        String[] modEntries = modData.trim().split("\n");

        for (String modEntry : modEntries) {

            ArrayList<String> modValues = new ArrayList<>();
            Matcher matcher = STRSPLIT_REGEX.matcher(modEntry.trim());

            while (matcher.find())
                modValues.add(matcher.group().trim());

            modifierEntry.type = mbEnums.ModType.valueOf(modValues.get(0).trim());

            switch (modifierEntry.type) {
                case AnimOverride:
                    modifierEntry.min = Float.parseFloat(modValues.get(1).trim());
                    modifierEntry.max = Float.parseFloat(modValues.get(2).trim());
                    break;
                case Health:
                case Mana:
                case Stamina:
                    modifierEntry.min = Float.parseFloat(modValues.get(1).trim());
                    modifierEntry.max = Float.parseFloat(modValues.get(2).trim());
                    modifierEntry.percentage = Float.parseFloat(modValues.get(3).trim());
                    modifierEntry.value = Float.parseFloat(modValues.get(4).trim()); // Always zero
                    modifierEntry.compoundCurveType = mbEnums.CompoundCurveType.valueOf(modValues.get(5).trim());
                    modifierEntry.arg1 = modValues.get(6).trim();
                    break;
                case Attr:
                case Resistance:
                case Skill:
                case HealthRecoverRate:
                case ManaRecoverRate:
                case StaminaRecoverRate:
                case DamageShield:
                case HealthFull:
                case ManaFull:
                case StaminaFull:
                case Slay:
                case Fade:
                case Durability:
                    modifierEntry.min = Float.parseFloat(modValues.get(1).trim());
                    modifierEntry.max = Float.parseFloat(modValues.get(2).trim());
                    modifierEntry.compoundCurveType = mbEnums.CompoundCurveType.valueOf(modValues.get(3).trim());

                    if (modValues.size() > 4)
                        modifierEntry.arg1 = modValues.get(4).trim();   // Some HeathFull entries do not have an argument
                    break;
                case MeleeDamageModifier:
                case OCV:
                case DCV:
                case AttackDelay:
                case AdjustAboveDmgCap:
                case DamageCap:
                case ArmorPiercing:
                case Speed:
                case PowerDamageModifier:
                case DR:
                case PassiveDefense:
                case MaxDamage:
                case Value:
                case WeaponSpeed:
                case MinDamage:
                case PowerCost:
                case Block:
                case Parry:
                case Dodge:
                case WeaponRange:
                case ScanRange:
                case ScaleHeight:
                case ScaleWidth:
                    modifierEntry.min = Float.parseFloat(modValues.get(1).trim());
                    modifierEntry.max = Float.parseFloat(modValues.get(2).trim());
                    modifierEntry.compoundCurveType = mbEnums.CompoundCurveType.valueOf(modValues.get(3).trim());
                    break;
                case ItemName:
                case BlockedPowerType:
                case ImmuneTo:
                case BlackMantle:
                    modifierEntry.arg1 = modValues.get(1).trim();

                    // Some BlockedPowerType entries have only one argument

                    if (modValues.size() > 2)
                        modifierEntry.arg2 = modValues.get(2).trim();
                    break;
                case NoMod:
                case ConstrainedAmbidexterity:
                case ProtectionFrom:
                case ExclusiveDamageCap:
                case IgnoreDamageCap:
                    modifierEntry.arg1 = modValues.get(1).trim();
                    break;
                case WeaponProc:
                    modifierEntry.min = Float.parseFloat(modValues.get(1).trim());
                    modifierEntry.arg1 = modValues.get(2).trim();
                    modifierEntry.max = Float.parseFloat(modValues.get(3).trim());
                    break;
                case BladeTrails:  // These tags have no parms or are not parsed
                case ImmuneToAttack:
                case ImmuneToPowers:
                case Ambidexterity:
                case Silenced:
                case IgnorePassiveDefense:
                case Stunned:
                case PowerCostHealth:
                case Charmed:
                case Fly:
                case CannotMove:
                case CannotTrack:
                case CannotAttack:
                case CannotCast:
                case SpireBlock:
                case Invisible:
                case SeeInvisible:
                    break;
                default:
                    Logger.error("Unhandled type: " + modifierEntry.type);
                    break;
            }
        }

        return modifierEntry;
    }

}
