import {ApiCall} from "tsrpc";
import {ReqRank, ResRank} from "../../cross/protocols/wzry/PtlRank";
import {player} from "../../shared/protocols/user/type";
import {Filter, FindOptions, OptionalId} from "mongodb";
import { CollectionRankList } from "../../module/collection_rank";

export async function getRankList(limit?: number, projection?: any, _where?:any) {
    let option: FindOptions = {
        sort: {
            'data.valArr': -1,
            'data.player.power': -1
        }
    }
    let filter:Filter<OptionalId<CollectionRankList>> = {type: 'wzryCross'};

    if (limit != null) {
        option.limit = limit;
    }
    if (projection != null) {
        option.projection = projection;
    }
    if (_where != null) {
        Object.assign(filter, _where);
    }

    let listArr = await G.mongodb.collection('rankList').find(filter, option).toArray();
    let list = listArr.map(l => l.data);

    return list;
}

export async function getPlayerRank(uid: string) {
    let _r = await getRankList(50, {
        "data.player.uid": 1,
        "data.valArr": 1,
    });
    if (!Object.keys(_r).length) {
        return -1
    }
    let myrank = _r.findIndex(li => li.player.uid == uid) + 1 || -1;
    return myrank;
}

export async function getWzryRankList(uid: string, gud: player) {
    let list = await getRankList(50);
    return {
        rankList: list,
        myRank: {
            rank: list.findIndex(li => li.player.uid == uid) + 1 || -1,
            player: gud,
            valArr: [(await G.mongodb.collection('wzry_fight').findOne({uid: uid}))?.jifen || 0]
        }
    };
}


export default async function (call: ApiCall<ReqRank, ResRank>) {
    let _r = await getWzryRankList(call.req.gud.uid, call.req.gud)
    _r.rankList = _r.rankList.splice(0, 50);
    call.succ(_r);
}