import {ApiCall} from "tsrpc";
import {PlayerFun} from "../../public/player";
import {ReqChangeName, ResChangeName} from "../../shared/protocols/user/PtlChangeName";
import {randomUUID} from "crypto";

export default async function (call: ApiCall<ReqChangeName, ResChangeName>) {
    let _name = call.req.name;

    // 名称已被使用
    let _user = await G.mongodb.collection('user').findOne({"name": _name});
    if (_user) {
        if (_name.slice(0, 6) == 'player') {
            _name = `player${randomUUID().slice(-6)}`
        } else return call.errorCode(-1);
    }

    let num = call.conn.gud.changeNameNum || 0;
    let need = G.gc.common.usercom.changename[num ? num - 1 : 0] || G.gc.common.usercom.changename.slice(-1)[0];

    if (need.n > 1) {
        await PlayerFun.checkNeedIsMeet(call, [need]);
        await PlayerFun.cutNeed(call, [need]);
    }
    await PlayerFun.addAttr(call, {name: _name, changeNameNum: num + 1});

    call.succ({});

    G.emit('PLAYER_CHANGE_NAME', call.conn.gud, _name);
}