import { ApiCall } from "tsrpc";
import { ReqGetEnemy, ResGetEnemy } from "../../../cross/protocols/hbzb/zbs/PtlGetEnemy";
import { Rank } from '../../../public/rank/rank';
import { rankInfo } from "../../../shared/protocols/type";
import { e } from "mathjs";

function rand(min:number,max:number){
    return Math.round(Math.random() * (max - min) + min);
}

export default async function (call: ApiCall<ReqGetEnemy, ResGetEnemy>) {
    let uid = call.req.uid;
    let myData = await G.mongodb.collection("hbzb_user_cross").findOne({uid:uid});
    let myRank = myData.rank;

    let enemyRank = [];
    let blackUids = [uid];

    if(myRank == 1){
        enemyRank = [4,3,2];
    }else if(myRank == 2){
        enemyRank = [4,3,1];
    }else if(myRank == 3){
        enemyRank = [4,2,1];
    }else{
        enemyRank = [
            rand(Math.floor(myRank*0.85-1),  Math.floor(myRank*0.7)),
            rand(Math.floor(myRank-1),  Math.floor(myRank*0.85)),
            rand(Math.floor(myRank*1.2),  Math.floor(myRank+1)),  
        ]
    }

    let enemys = await G.mongodb.collection("hbzb_user_cross").find({
        zbsgroup:myData.zbsgroup,
        uid : {$nin: blackUids},
        rank: {$in: enemyRank}
    }).toArray();

    call.succ({
        enemy: enemys.map((e, i) => ({
            data: e.data as any,
            rank: e.rank
        })),
        rank: myRank
    });
}