import { ApiCall } from "tsrpc";
import { GHManage } from '../../public/gonghui/manage';
import { ReqJoin, ResJoin } from "../../shared/protocols/gonghui/PtlJoin";
import { HongDianChange } from "../hongdian/fun";
import {PublicShared} from "../../shared/public/public";

export default async function (call: ApiCall<ReqJoin, ResJoin>) {
    if (PublicShared.getOpenServerDay() > 1) {
        if ((call.conn.gud.ghExitTime || 0) + G.gc.com.Guild_CD.value > G.time) {
            return call.error(globalThis.lng.gonghui_5);
        }
    }

    if (call.conn.gud.ghId) return call.error(globalThis.lng.gonghui_16);

    const gh = await GHManage.getGH(call.req.id);

    if (!gh) return call.error(globalThis.lng.gonghui_17);

    if (gh.data.players.length >= gh.maxPlayerNum) return call.error(globalThis.lng.gonghui_18);

    if (call.conn.gud.lv < gh.data.setting.joinLv) return call.error(globalThis.lng.gonghui_19);

    if (gh.data.setting.autoJoin) {
        gh.addPlayer(call.conn.gud);
    } else {
        gh.addApply(call.conn.gud);
        let _ghUsers = await gh.getAllPlayers();
        _ghUsers.forEach(ele => {
            if (ele.player.ghLevel != 3) {
                HongDianChange.sendChangeKey(ele.player.uid, ['gonghuihd'])
            }
        })
    }

    call.succ({});
}