import { readFileAndParse, parseNumberList, parseGoodStr, decodeArrayListStr } from '../util'
import { FILENAME } from '../../consts'
import { RewardInter } from '../interface';

export interface DicGacha {
    // 抽卡id
    readonly id: number;
    // 抽卡次数 1次，10次
    readonly count: number[];
    // 免费次数
    readonly free: { day: number, count: number };
    // 消耗的招募券
    readonly cost: RewardInter[];
    // 概率
    readonly percent: { id: number, weight: number }[];
    // 哪一个是大奖
    readonly floorReward: number;
}

export const dicGacha = new Map<number, DicGacha>(); // id => dic
export function loadGacha() {
    dicGacha.clear();
    let arr = readFileAndParse(FILENAME.DIC_GACHA);

    arr.forEach(o => {
        o.count = parseNumberList(o.count);
        o.free = parseFree(o.free);
        o.cost = parseGoodStr(o.cost);
        o.percent = parsePercent(o.percent);
        dicGacha.set(o.id, o);
    });
    arr = undefined;
}

function parseFree(str: string) {
    let arr = parseNumberList(str);
    if(arr.length > 0 && arr.length != 2) {
        throw new Error('dic_gacha free format err');
    }
    if(arr.length == 0) {
        return { day: 0, count: 0 }
    } else {
        return { day: arr[0], count: arr[1] }
    }
}

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