import { League, MaxCpByLeague } from 'app/models/League';
import { LevelMultipliers } from 'app/models/LevelMultipliers';
import { IBaseStats } from 'app/models/Pokemon';

const calculateStatsFormula = (baseStats : IBaseStats, ivHp : number, ivAtk : number, ivDef : number) => Math.sqrt(baseStats.baseStamina + ivHp) * Math.sqrt(baseStats.baseDefense + ivDef) * (baseStats.baseAttack + ivAtk);

const calculateCpByLevelMultiplier = (statsFormula : number, levelMultiplier : number) => Math.floor((statsFormula * Math.pow(levelMultiplier, 2)) / 10);

export const calculateCp = (baseStats : IBaseStats, level : number, ivHp : number, ivAtk : number, ivDef : number) => {
    const statsFormula = calculateStatsFormula(baseStats, ivHp, ivAtk, ivDef);
    const levelMultiplier = LevelMultipliers[(level - 1) * 2];
    const cp = calculateCpByLevelMultiplier(statsFormula, levelMultiplier);
    return cp;
};

export const calculateStatAtLevel = (level : number, baseStatValue : number, ivStat : number) => {
    const levelMultiplier = LevelMultipliers[(level - 1) * 2];
    const calculatedStat = Math.floor((baseStatValue + ivStat) * levelMultiplier);
    return calculatedStat;
};

export const calculateMaxLevelForLeague = (baseStats : IBaseStats, ivHp : number, ivAtk : number, ivDef : number, league : League) => {
    const maxCp = MaxCpByLeague[league];
    const statsFormula = calculateStatsFormula(baseStats, ivHp, ivAtk, ivDef);
    let level = 1;
    for (let i = LevelMultipliers.length - 1; i >= 0; i--) {
        const cp = calculateCpByLevelMultiplier(statsFormula, LevelMultipliers[i]);
        if (cp <= maxCp) {
            level = (i / 2) + 1;
            break;
        }
    }
    return level;
};
