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

export interface DicGoods {
    // 物品id
    readonly good_id: number;
    // 物品名
    readonly name: string;
    // 物品品质
    readonly quality: number;

    // 类型id
    readonly itid: number;
    // 物品类型
    readonly goodType: number;

    // 分解所得
    readonly decomposeItem: Array<RewardInter>;
    // 将魂对应武将id
    readonly hid: number;
    // 属性外加的值，经验，好感
    readonly value: number;

    readonly count?: number;

    // 解锁条件
    readonly condition: { id: number, type: number, params: number[] }[];
    // 时间限制
    readonly timeLimit: number;
    // 图片
    readonly image_id: number;
    // 礼包id
    readonly gift: number;
    // 是否可以用于pvp随机
    readonly randomShow: number;
}

type KeysEnum<T> = { [P in keyof Required<T>]: true };
const DicGoodsKeys: KeysEnum<DicGoods> = {
    good_id: true,
    name: true,
    decomposeItem: true,
    quality: true,
    itid: true,
    goodType: true,
    hid: true,
    value: true,
    count: true,
    condition: true,
    timeLimit: true,
    image_id: true,
    gift: true,
    randomShow: true,
}
export const dicGoods = new Map<number, DicGoods>();
export const figureCondition = new Map<number, { params: number[], id: number, gid: number }[]>(); // type => {params, id, gid}

export function loadGoods() {
    dicGoods.clear();
    figureCondition.clear();
    
    let arr = readFileAndParse(FILENAME.DIC_GOODS);

    arr.forEach(o => {
        o.decomposeItem = parseGoodStr(o.decomposeItem);
        o.timeLimit = o.timelimit;
        let condition = parseConditionStr(o.condition);
        for (let { id, type, params } of condition) {
            let mapArr = figureCondition.get(type) || new Array<{ params: number[], id: number, gid: number }>();
            mapArr.push({ params, id: id, gid: o.good_id });
            figureCondition.set(type, mapArr);
        }
        o.condition = condition;
        dicGoods.set(o.good_id, _.pick(o, Object.keys(DicGoodsKeys)));
    });

    arr = undefined;
}

// 解析物品 {"type": number, "param": number} 格式
export function parseConditionStr(str: string) {
    let result = new Array<{ id: number, type: number, params: number[] }>();
    if (!str) return result;
    let decodeArr = decodeArrayListStr(str);
    for (let i = 0; i < decodeArr.length; i++) {
        let [type, ...params] = decodeArr[i];

        if (isNaN(parseInt(type))) {
            throw new Error('data table format wrong');
        }
        let parsedParam = new Array<number>();
        for (let param of params) {
            if (isNaN(parseInt(param))) {
                throw new Error('data table format wrong');
            }
            parsedParam.push(parseInt(param))
        }
        result.push({ id: i + 1, type: parseInt(type), params: parsedParam });
    }
    return result
}
