import { ApiCall } from "tsrpc";
import { HeroFun } from '../../public/hero';
import { ReqTalent, ResTalent } from "../../shared/protocols/hero/PtlTalent";

export default async function (call: ApiCall<ReqTalent, ResTalent>) {
    let typeConf = G.gc.hero_tf[call.req.type];
    if (!typeConf) return call.error('', { code: -1 });

    let hero = await HeroFun.getHero(call, call.req._id)
    if (!hero) return call.error('', { code: -2 });

    let talent = hero.talent || Object.fromEntries(Object.keys(G.gc.hero_tf).map(t => [t, 0]));
    let conf = typeConf[talent[call.req.type] + 1];
    if (!conf) return call.error('', { code: -3 });

    let pre = conf.unlock;
    // if (pre && talent[pre] < Object.keys(pre).length) return call.error('', { code: -4 });
    if (pre.length > 0) {
        for (let type of pre) {
            if (talent[type] < Object.values(G.gc.hero_tf[type]).slice(-1)[0].lv) return call.error('', { code: -4 });
        }
    }

    let allPoint = G.gc.hero_jx[hero.awake]?.talent_point || 0;
    let usePoints = Object.entries(talent).map(v => new Array(v[1]).fill(1).map((_v, i) => G.gc.hero_tf[v[0]][i + 1].cos)).reduce((a, b) => a.concat(b));
    let usePoint = usePoints.length > 0 ? usePoints.reduce((a, b) => a + b) : 0;

    if (allPoint - usePoint < conf.cos) return call.error('', { code: -4 });
    talent[call.req.type]++;

    await HeroFun.changeHeroAttr(call, hero, {talent: talent});
    call.succ({});
}