import { ApiCall } from "tsrpc";
import { FriendManage } from '../../public/friend/manage';
import { PlayerFun } from '../../public/player';
import { ReqGift, ResGift } from "../../shared/protocols/friend/PtlGift";
import { PublicShared } from '../../shared/public/public';

export default async function (call: ApiCall<ReqGift, ResGift>) {
    let prize: atn[] = [];
    let my = await FriendManage.getFriend(call.uid);
    let change: ResGift['change'] = {};

    if (call.req.type != 'yijian') {
        if (!call.req.uid) return call.error(globalThis.lng.friend_9);
        if (!my.data.friendList.includes(call.req.uid)) return call.error(globalThis.lng.friend_9);
    }

    switch (call.req.type) {
        case 'get':
            if (my.data.recGift.includes(call.req.uid)) return call.error(globalThis.lng.friend_10);
            if (my.data.recGift.length >= G.gc.friend.maxGetGiftNum) return call.error(globalThis.lng.friend_11);
            if (!my.data.getGift[call.req.uid] || my.data.getGift[call.req.uid] < PublicShared.getToDayZeroTime()) return call.error(globalThis.lng.friend_12);
            prize.push(...PublicShared.randomDropGroup(G.gc.friend.giftPrize));
            my.recGift(call.req.uid);
            change.recGift = my.data.recGift;
            break;
        case 'send':
            if (my.data.sendGift.includes(call.req.uid)) return call.error(globalThis.lng.friend_13);
            if (my.data.sendGift.length >= G.gc.friend.maxSendGiftNum) return call.error(globalThis.lng.friend_14);
            my.sendGift(call.req.uid);
            change.sendGift = my.data.sendGift;
            break;
        case 'yijian':
            if (my.data.recGift.length < G.gc.friend.maxGetGiftNum && Object.keys(my.data.getGift).length > my.data.recGift.length) {
                let recUids = Object.keys(my.data.getGift).difference(my.data.recGift).slice(0, G.gc.friend.maxGetGiftNum - my.data.recGift.length);
                prize.push(...PublicShared.randomDropGroup(G.gc.friend.giftPrize, recUids.length));
                my.recGift(recUids);
                change.recGift = my.data.recGift;
            }
            if (my.data.sendGift.length < G.gc.friend.maxSendGiftNum && my.data.sendGift.length < my.data.friendList.length) {
                let sendUids = my.data.friendList.difference(my.data.sendGift).slice(0, G.gc.friend.maxSendGiftNum - my.data.sendGift.length);
                my.sendGift(sendUids);
                change.sendGift = my.data.sendGift;
            }
            break;
    }

    prize.length > 0 && await PlayerFun.sendPrize(call, prize);

    if(prize.length == 0 && !change.sendGift?.length ) {
        return call.error(lng.friend_23)
    } else {
        call.succ({
            prize: prize,
            change: change
        });
    }
}