import { ApiCall } from "tsrpc";
import { ReqSelect, ResSelect } from "../../shared/protocols/ganhai/PtlSelect";
import { HongDianChange } from "../hongdian/fun";
import { GanHaiRed, randomMyShips } from './ApiOpen';

export default async function (call: ApiCall<ReqSelect, ResSelect>) {
    let dbData = await G.mongodb.collection('ganhai').findOne({ uid: call.uid });
    let escortNum = dbData.useEscortNum + 1;

    if (escortNum > G.gc.ganhai.escortNum) return call.error('', { code: 0 });
    if (dbData.ship != null) return call.error('', { code: -1 });
    if (dbData.myShips[call.req.index] == undefined) return call.error('', { code: -2 });

    let obj = {
        index: dbData.myShips[call.req.index],
        sTime: G.time,
        beFightNum: 0,
        player: await call.conn.getDefaultFightData()
    };
    let shipIndex = randomMyShips();

    G.mongodb.collection('ganhai').updateOne({ uid: call.uid }, { $set: { myShips: shipIndex, ship: obj, useEscortNum: escortNum } });
    HongDianChange.sendChangeKey(call.uid, ['gonghuihd']);
    GanHaiRed.addList(call.uid, obj);

    call.succ({
        change: {
            ship: obj,
            myShips: shipIndex,
            useEscortNum: escortNum
        }
    });
}