import { ApiCall } from "tsrpc";
import { ChatFun } from '../../public/chat';
import { FriendManage } from '../../public/friend/manage';
import { ReqPrivate, ResPrivate } from "../../shared/protocols/chat/PtlPrivate";
import { MsgPrivate } from '../../shared/protocols/msg_s2c/MsgPrivate';
import { getGud } from "../../public/gud";

export default async function (call: ApiCall<ReqPrivate, ResPrivate>) {
    let my = await FriendManage.getFriend(call.uid);

    if (!my.data.friendList.includes(call.req.uid)) return call.errorCode(-1);

    let privateId = [call.uid, call.req.uid].sort().join('&');

    ChatFun.writePrivateId(call.uid, privateId);
    ChatFun.writePrivateId(call.req.uid, privateId);

    //let recipient = await G.mongodb.collection('user').findOne({ uid: call.req.uid });
    let recipient = await getGud( call.req.uid );
    let msg: MsgPrivate = {
        msg: call.req.msg,
        time: G.time,
        sender: call.conn.gud,
        privateId: privateId,
        otherData: {
            uids: [call.req.uid, call.uid]
        },
        recipient: recipient
    };

    // 原私聊记录表，保留。
    G.mongodb.collection('chat').updateOne(
        { type: privateId },
        { $push: { list: msg } },
        { upsert: true }
    );
    // 写入聊天记录
    let msgLog = {
        content: call.req.msg,
        toUid: call.req.uid,
        type: 'private',
    }
    ChatFun.setChatLog(call, msgLog)

    G.server.sendMsgByUid(call.uid, 'msg_s2c/Private', msg);
    G.server.sendMsgByUid(call.req.uid, 'msg_s2c/Private', msg);

    call.succ({});
}