// 镇念塔派遣任务表
import {parseGoodStr, decodeArrayListStr, decodeArrayStr, readFileAndParse} from '../util'
import { FILENAME } from '../../consts';
import { RewardInter } from '../interface';

interface SuitFloor {
    min: number;
    max?: number;
}

export interface DicTowerTask {
    // 任务id
    readonly taskId: number;
    // 任务名称
    readonly taskName: string;
    // 任务品质
    readonly quality: number;
    // 任务奖励
    readonly reward: Array<RewardInter>;
    // 额外奖励
    readonly additionalReward: Array<RewardInter>;
    // 达成额外奖励需要的武将条件
    readonly termsForAdd: Array<{type: number, param: number, count: number}>;
    // 完成任务所需的武将数
    readonly actorNeeded: number;
    // 完成时间（秒）
    readonly completeTime: number;
    // 适用层数，此处层数是指通过了的层数
    readonly suitFloor: SuitFloor;
    // 权重
    readonly weight: number;

}

export const dicTowerTask = new Map<number, DicTowerTask>();
export function loadTowerTask() {
    dicTowerTask.clear();
    
    let arr = readFileAndParse(FILENAME.DIC_TOWER_TASK);

    arr.forEach(o => {
        o.reward = parseGoodStr(o.reward);
        o.additionalReward = parseGoodStr(o.additionalReward);
        o.termsForAdd = parseTermsForAdd(o.termsForAdd);
        o.suitFloor = parseSuitFloor(o.suitFloor as string);
        dicTowerTask.set(o.taskId, o);
    });
    arr = undefined;
}

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

function parseSuitFloor(str: string) {
    if(!str) return {min: 0}
    let decodeArr = decodeArrayStr(str, '&');
    let [min, max] = decodeArr;
    if(max) {
      if(isNaN(parseInt(min)) || isNaN(parseInt(max))) throw new Error('data table format wrong');
      return {min: parseInt(min), max: parseInt(max)};
    } else { // 最大值如果不存在则表示 >= min
      if(isNaN(parseInt(min))) throw new Error('data table format wrong');
      return {min: parseInt(min)};
    }
}