// GVG千机阁
import { FILENAME } from '../../consts';
import { decodeArrayListStr, parseNumberList, readFileAndParse } from '../util';
const _ = require('lodash');

export interface DicGVGResourceBase {
    // 唯一id
    readonly id: number;
    // 名称
    readonly name: string
    // 农庄等级
    readonly lv: number;
    // 类型 1-农田 2-矿场 3-木堆
    readonly type: number;
    // 限制类型
    readonly limitType: number;
    // 限制参数
    readonly limitParams: number[];
    // 农田产量加成
    readonly fieldAdd: number;
    // 矿山铁矿的含铁量
    readonly mineralValue: { type: number, output: number, count: number }[];
    // 单木框产量
    readonly woodOutput: number;
    // 总数
    readonly sum: number;
}

type KeysEnum<T> = { [P in keyof Required<T>]: true };
const DicGVGResourceBaseKeys: KeysEnum<DicGVGResourceBase> = {
    id: true, name: true, lv: true, type: true, limitType: true, limitParams: true, fieldAdd: true, mineralValue: true, woodOutput: true, sum: true
}
export const dicGVGResourceBase = new Map<number, DicGVGResourceBase>(); // id => DicGVGResourceBase
export const dicGVGResourceBaseByType = new Map<number, number[]>(); // type => [id]
export const dicGVGResourceBaseByLv = new Map<string, number>();  // type + lv => [id]
export function loadGVGResourceBase() {
    dicGVGResourceBase.clear();
    dicGVGResourceBaseByType.clear();
    dicGVGResourceBaseByLv.clear();
    
    let arr = readFileAndParse(FILENAME.DIC_GVG_RESOURCE_BASE);
    arr.forEach(o => {
        o.limitParams = parseNumberList(o.limitParams);
        if(o.type == 1) { // 农田
            o.fieldAdd = parseFloat(o.value.split('&')[1]);
            if(isNaN(o.fieldAdd)) throw new Error('data table format wrong');
        } else if (o.type == 2) { // 矿山
            o.mineralValue = parseMineralValue(o.value);
        } else if (o.type == 3) {
            o.woodOutput = parseFloat(o.value.split('&')[1]);
            if(isNaN(o.woodOutput)) throw new Error('data table format wrong');
        }
        dicGVGResourceBase.set(o.id, _.pick(o, Object.keys(DicGVGResourceBaseKeys)));
        dicGVGResourceBaseByLv.set(`${o.type}_${o.lv}`, o.id);
        if(!dicGVGResourceBaseByType.has(o.type)) {
            dicGVGResourceBaseByType.set(o.type, []);
        }
        dicGVGResourceBaseByType.get(o.type)?.push(o.id);
    });
    arr = undefined;
}

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