import { Friend } from './friend';
import { CollectionFriend } from '../../module/collection_friend';
import { clusterRunOnce } from '../../clusterUtils';

export class FriendManage {
    static list: k_v<Friend> = {};
    static async init() {
        //改用redis后，只需要第一个进程来干
        clusterRunOnce(async () => {
            const arr = await G.mongodb.collection('friend').find({}).toArray();
            arr.forEach(a => {
                if(a.uid) {
                    this.setFriend(a.uid, a)
                    if(!a.myApplyList) new Friend(a)
                }
            });
        })
    }
    
    static setFriend(uid: string, data: CollectionFriend) {
        G.redis.hSet('friend:list', uid, data)
        return 
    }

    static async getFriend(uid: string): Promise<Friend|undefined> {
        let data:CollectionFriend = await G.redis.hGet('friend:list', uid)
        if(!data) {
            data = await G.mongodb.collection('friend').findOne({uid})
            if(data) this.setFriend(uid, data)
        }
        if(data) return new Friend(data)
        return undefined
    }

    static async addNew(uid: string) {
        let data = await this.getFriend(uid)
        if (!data) {
            let newData = new Friend({
                uid: uid,
                refreshTime: G.time,
                recGift: [],
                getGift: {},
                sendGift: [],
                applyList: [],
                blacklist: [],
                friendList: [],
                myApplyList: []
            });
            G.mongodb.collection('friend').insertOne(newData.data);
        }
    }
}