import { ApiCall } from "tsrpc";
import { EquipFun } from '../../public/equip';
import { HeroFun } from '../../public/hero';
import { PlayerFun } from '../../public/player';
import { ReqAdjustment, ResAdjustment } from "../../shared/protocols/equip/PtlAdjustment";
import { EquipShared } from '../../shared/public/equip';
import { PublicShared } from '../../shared/public/public';

export default async function (call: ApiCall<ReqAdjustment, ResAdjustment>) {

    let equip = await EquipFun.getEquip(call, call.req.equipId);
    if (!equip) return call.error('', { code: 0 });

    let curLv = equip.adjustment || 0;
    if (!G.gc.equipAdjusting[curLv + 1]) return call.error('', { code: -1 });

    let addLv = 0;
    let allNeed: atn[] = [];

    for (let i = 1; i <= call.req.num; i++) {
        let conf = G.gc.equipAdjusting[curLv + i];
        if (!conf) break;
        let isMeet = await PlayerFun.checkNeedIsMeet(call, PublicShared.mergePrize(allNeed.concat(conf.need)), false);
        if (!isMeet.isOk) {
            if (addLv == 0) {
                return call.error('', { code: -104, atn: isMeet.atn });
            } else {
                break;
            }
        }
        addLv++;
        allNeed.push(...conf.need);
    }

    await PlayerFun.cutNeed(call, allNeed);
    await EquipFun.changeEquipAttr(call, equip, { adjustment: curLv + addLv });

    if (equip.wearaId) {
        let hero = await HeroFun.getHero(call, equip.wearaId);
        if (hero) {
            let wearData = hero.equip || {};
            wearData[G.gc.equip[equip.equipId].type] = EquipShared.fmtEquip(equip);
            await HeroFun.changeHeroAttr(call, hero, { equip: wearData });
        }
    }

    call.succ({});
}