// 物品表
import { decodeArrayListStr, readFileAndParse, parseGoodStr } from '../util'
import { FILENAME, ABI_TYPE} from '../../consts'
const _ = require('lodash');

export interface SpecialMaterial {
    readonly ids: number[]; 
    readonly count: number;
}

export interface DicTitle {
    readonly id: number;
    // 等级
    readonly mainAttrValue: Map<number, number>; // id => value 这里的值是上一级的基础上增加的值
    readonly assiAttrValue: Map<number, number>; // id => value
    // 等级现在
    readonly lvLimited: number;
    // 升级消耗
    readonly material:Array<{id: number, number: number}>;
}

type KeysEnum<T> = { [P in keyof Required<T>]: true };
const DicTitleKeys: KeysEnum<DicTitle> = {
    id: true, 
    mainAttrValue: true, 
    assiAttrValue: true, 
    lvLimited: true, 
    material: true
}
export const dicTitle = new Map<number, DicTitle>();
export function loadTitle() {
    dicTitle.clear();
    
    let arr = readFileAndParse(FILENAME.DIC_TITLE);

    arr.forEach(o => {
        o.mainAttrValue = parseMainAttr(o);
        o.assiAttrValue = parseAttr(o.pdi, o.mdi, o.assiAttrValue);
        o.material = parseGoodStr(o.material);
        dicTitle.set(o.id, _.pick(o, Object.keys(DicTitleKeys)));
    });
    
    arr = undefined;
}

function parseAttr(pdi: number, mdi: number, str: string) {
    let result = new Map<number, number>();
    if(!str) return result;
    let decodeArr = decodeArrayListStr(str);
    for(let [id, value] of decodeArr) {
        if(isNaN(parseInt(id)) || isNaN(parseInt(value))) {
            throw new Error('data table format wrong');
        }
        result.set(parseInt(id), parseInt(value));
    } 

    result.set(ABI_TYPE.ABI_PHYSICAL_DAMAGE_INCREASE, pdi);
    result.set(ABI_TYPE.ABI_MAGIC_DAMAGE_INCREASE, mdi);

    return result
}

function parseMainAttr(elem) {
    let result = new Map<number, number>();
    result.set(ABI_TYPE.ABI_HP, elem.hp);
    result.set(ABI_TYPE.ABI_ATK, elem.atk);
    result.set(ABI_TYPE.ABI_DEF, elem.def);
    result.set(ABI_TYPE.ABI_MDEF, elem.mdef);
    return result;
}