// 武将升星表
import { decodeArrayListStr, parseNumberList, readFileAndParse } from '../util'
import { FILENAME } from '../../consts';
const _ = require('lodash');

export interface DicHeroTalent {
    // 唯一id
    readonly id: number;
    // 天赋组id
    readonly talentId: number;
    // 节点层数
    readonly nodeSort: number;
    // 和其他节点关系
    readonly relation: [{ type: number, ids?: number[] }];
    // 节点等级数
    readonly level: [{ lv: number, seid: number, cost: number }];
    // 前置节点
    readonly prepositionId: number[][];
    // 需要满足在天赋树中累计消耗n点天赋点
    readonly preTotalPoint: number;
    // 在前置节点中消耗至少n点天赋点（在有多个前置节点时，取最高的1个）
    readonly preSinglePoint: number;
}


type KeysEnum<T> = { [P in keyof Required<T>]: true };
const DicHeroTalentKeys: KeysEnum<DicHeroTalent> = {id: true, talentId: true, nodeSort: true, relation: true, level: true, prepositionId: true, preTotalPoint: true, preSinglePoint: true};

export const dicHeroTalent = new Map<number, DicHeroTalent>();
export const initTalents = new Map<number, number[]>();
export function loadHeroTalent() {
    dicHeroTalent.clear();
    initTalents.clear();
    
    let arr = readFileAndParse(FILENAME.DIC_HERO_TALENT);
    
    arr.forEach(o => {
        o.relation = parseRelation(o.type, o.relationId);
        o.level = parseLevel(o.levelCount, o.levelSeid, o.levelConsume);
        o.prepositionId = parsePrePositionId(o.prepositionId);
        dicHeroTalent.set(o.id, _.pick(o, Object.keys(DicHeroTalentKeys)));
        if(o.prepositionId.length == 0 && o.levelConsume == '&') {
            if(!initTalents.has(o.talentId)) {
                initTalents.set(o.talentId, []);
            }
            initTalents.get(o.talentId).push(o.id);
        }
    });
    arr = undefined;
}

function parseRelation(type: string, relationId: string) {
    let relation: {type: number, ids?: number[]}[] = [];
    let types = parseNumberList(type);
    let relations = decodeArrayListStr(relationId);
    for(let i = 0; i < types.length; i++) {
        if(relations[i]) {
            relation.push({
                type: types[i],
                ids: relations[i].map(id => parseInt(id))
            });
        }
    }
    return relation;
}

function parseLevel(levelCount: number, levelSeid: string, levelConsume: string) {
    let levelSeids = parseNumberList(levelSeid);
    let levelConsumes = parseNumberList(levelConsume);
    let level: { lv: number, seid: number, cost: number }[] = [];
    for(let i = 0; i < levelCount; i++) {
        level.push({ lv: i + 1, seid: levelSeids[i]||0, cost: levelConsumes[i]||0});
    }
    return level;
}

function parsePrePositionId(str: string) {
    let arr = decodeArrayListStr(str);
    return arr.map(arr1 => {
        return arr1.map(str => parseInt(str));
    });
}