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

export interface DicGacha {
    // 抽卡id
    readonly id: number;
    // 抽卡类型
    readonly gachaType: GACHA_TYPE;
    // 保底类型, dic_zyz_gachaFloor的id
    readonly floor: number[];
    // 抽卡次数 1次，10次
    readonly count: number[];
    // 免费次数
    readonly free: { day: number, count: number };
    // 消耗的招募券
    readonly cost: RewardInter[];
    // 概率
    readonly percent: { planId: number, weight: number }[];
    // 是否计入任务
    readonly isTask: number;
    // 玩家抽卡次数范围
    readonly gachaCnt: { min: number, max: number };
    // 是否显示在主界面
    readonly showInMainPage: number;
}

export const dicGacha = new Map<number, DicGacha>(); // id => dic
export const dicGachaByGachaType = new Map<number, number[]>(); // gachaType => id
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.floor = parseNumberList(o.floor);
        o.cost = parseGoodStr(o.cost);
        o.percent = parsePercent(o.percent);
        o.gachaCnt = parseGachaCnt(o.gachaCnt);
        dicGacha.set(o.id, o);
        if(!dicGachaByGachaType.has(o.gachaType)) {
            dicGachaByGachaType.set(o.gachaType, []);
        }
        dicGachaByGachaType.get(o.gachaType).push(o.id);
    });
    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<{ planId: number, weight: number }>();
    if (!str) return result;
    let decodeArr = decodeArrayListStr(str);
    for (let [planId, weight] of decodeArr) {
        if (isNaN(parseInt(planId)) || isNaN(parseInt(weight))) {
            throw new Error('data table format wrong');
        }
        result.push({ planId: parseInt(planId), weight: Math.floor(parseFloat(weight) * 10) });
    }
    return result
}

function parseGachaCnt(str: string) {
    let arr = parseNumberList(str);
    return { min: arr[0]||0, max: arr[1]||-1 }
}