import { readFileAndParse } from '../util'
import { FILENAME } from '../../consts'
import { decodeArrayListStr } from '../../pubUtils/util';

export interface AuctionBasicPool {
    readonly id: number; // 物品id
    readonly count: number; // 数量
    readonly weight: number; // 随机权重
}

export interface DicAuctionBasicPool {
    readonly id: number;   // 唯一id
    readonly rewardBasicPool: AuctionBasicPool[];
    readonly basePrice: number;
    readonly maxPrice: number;
    readonly sort: number; // 排序
}

export interface DicAuctionReward {

    readonly poolId: number;
    // 目标品质
    readonly rewardId: { id: number; count: number; }[]
}

interface DicAuctionPool {
    readonly id: number;     // basicPool的id
    readonly count: number;  // 份数
    readonly basicPool: DicAuctionBasicPool; // 随机池
}

export const dicAuctionPool = new Map<number, DicAuctionPool[]>(); // poolId => DicAuctionPool
export function loadAuctionReward() {
    dicAuctionPool.clear();
    let basicPoolMap = new Map<number, DicAuctionBasicPool>(); // id => AuctionBasicPool
    let arr = readFileAndParse(FILENAME.DIC_AUCTION_BASIC_POOL);
    arr.forEach(o => {
        o.rewardBasicPool = parseRewardBasicPool(o.rewardBasicPool);
        o.basePrice = parsePrice(o.basePrice);
        o.maxPrice = parsePrice(o.maxPrice);
        basicPoolMap.set(o.id, o);
    });
    arr = undefined;
    let arr2 = readFileAndParse(FILENAME.DIC_AUCTION_REWARD);
    arr2.forEach(o => {
        let rewardId = parseRewardId(o.rewardId);
        dicAuctionPool.set(o.poolId, rewardId.map(({ id, count }) => {
            let basicPool = basicPoolMap.get(id);
            return { id, count, basicPool}
        }));
    });
    arr2 = undefined;
}

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

function parsePrice(str: string) {
    let arr = str.split('&');
    if(arr.length != 2) return 0;
    let price = parseInt(arr[1]);
    if(isNaN(price)) throw new Error('price format wrong');
    return price;
}

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