// 兵种表
import { readFileAndParse, parseNumberList, parseGoodStr, decodeArrayListStr} from '../util'
import { FILENAME, } from '../../consts'
import { RewardInter } from '../interface';
const _ = require('lodash');

export interface DicJob {
    // 兵种id
    readonly jobid: number;
    // 兵种名
    readonly name: string;
    // 该兵种在大兵种中的阶段
    readonly grade: number;
    // 解锁等级
    readonly unlockLevel: number;
    // 兵种类别
    readonly job_class: number;
    // 职业类别
    readonly type: number;
    // 特性
    readonly seid: Array<number>;
    // 训练消耗
    readonly trainingConsume: Array<RewardInter>;
    // 升阶消耗
    readonly upGradeConsume: Array<RewardInter>;
    // 每阶升级属性
    readonly ceAttr: Map<number, {id: number, attr: number}>;
    // 一共有多少阶升级
    readonly maxStage: number;

}

type KeysEnum<T> = { [P in keyof Required<T>]: true };
const DicJobKeys: KeysEnum<DicJob> = {jobid: true, name: true, grade: true, unlockLevel: true, job_class: true, type: true, seid: true,trainingConsume: true, upGradeConsume: true, ceAttr: true, maxStage: true};

export const dicJob = new Map<number, DicJob>();
export const jobClassMaxGrades = new Map<number, {grade:number, jobid:number}>();
export const jobClassAndgrades = new Map<string, {jobid:number, unlockLevel:number}>();

export function loadJob() {
    dicJob.clear();
    jobClassMaxGrades.clear();
    jobClassAndgrades.clear();
    
    let arr = readFileAndParse(FILENAME.DIC_JOB);

    arr.forEach(o => {
        if(o.isPlayer) {
            o.seid = parseNumberList(o.seid);
            o.trainingConsume = parseGoodStr(o.trainingConsume);
            o.maxStage = o.trainingConsume.length;
            o.upGradeConsume = parseGoodStr(o.upGradeConsume);
            o.ceAttr = parseCeAttr(o.maxStage, o.attr);
            dicJob.set(o.jobid, _.pick(o, Object.keys(DicJobKeys)));
            let jobClass = jobClassMaxGrades.get(o.job_class);
            if (!jobClass || jobClass.grade < o.grade) {
                jobClassMaxGrades.set(o.job_class, {grade: o.grade,jobid: o.jobid});
            }
            jobClassAndgrades.set(o.job_class+'_'+o.grade,{unlockLevel:o.unlockLevel, jobid:o.jobid});    
        }
    });
    arr = undefined;
}

function parseCeAttr(maxStage: number, str: string) {
    let result = new Map<number, { id: number, attr: number }>();
    if (!str) return result;
    let decodeArr = decodeArrayListStr(str);
    for (let i = 1; i <= maxStage; i++) {
        let [id, attr] = decodeArr[i - 1]||[i.toString(), "0"];
        if (isNaN(parseInt(id)) || isNaN(parseInt(attr))) {
            throw new Error('data table format wrong');
        }
        result.set(i, { id: parseInt(id), attr: parseFloat(attr) });
    }
    return result
}