import { decodeArrayListStr, readFileAndParse } from '../util'
import { FILENAME } from '../../consts'
type KeysEnum<T> = { [P in keyof Required<T>]: true };
const _ = require('lodash');

export interface DicTowerPvpSubAttr {
    // 对应 dicPvpDifficultRatio表的同名字段
    readonly secondAttrLevel: number;
    // 属性
    readonly secondAtr: {id: number, val: number}[];
}

const DicTowerPvpSubAttrKeys: KeysEnum<DicTowerPvpSubAttr> = {
    secondAttrLevel: true,
    secondAtr: true,
};

export const dicTowerPvpSubAttr = new Map<number, DicTowerPvpSubAttr>();
export function loadTowerPvpSubAttr() {
    dicTowerPvpSubAttr.clear();
    let arr = readFileAndParse(FILENAME.DIC_TOWER_PVP_SUB_ATTR);
    arr.forEach(o => {
        o.secondAtr = parseAttr(o.secondAtr);
        dicTowerPvpSubAttr.set(o.secondAttrLevel, _.pick(o, Object.keys(DicTowerPvpSubAttrKeys)));
    });
    arr = undefined;
}

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