import { Application, BackendSession } from "pinus";
import { ScriptBarrageModel } from "../../../db/ScriptBarrage";
import { BarrageReturn } from '../../../domain/roleField/barrage';
import { resResult, getRandEelm } from "../../../pubUtils/util";
import { STATUS } from "../../../consts";

export default function(app: Application) {
    return new BarrageHandler(app);
}

export class BarrageHandler {
    constructor(private app: Application) {
    }

    public async sendBarrage(msg: { warId: number, rid: string, index: string, content: string }, session: BackendSession) {
        const roleId: string = session.get('roleId');
        const { warId, rid, index, content } = msg;
        const result = await ScriptBarrageModel.createBarrage(roleId, warId, rid, index, content);
        let barrageList: BarrageReturn[] = [];
        let bs = new BarrageReturn(result);
        barrageList.push(bs);
        return resResult(STATUS.SUCCESS, { barrageList });
    }

    public async getBarrageList(msg: {rid: string}, session: BackendSession) {
        // const roleId: string = session.get('roleId');
        const { rid } = msg;
        const result = await ScriptBarrageModel.getBarrageList(rid, 1000);
        const perMax = 10, max = 50; // 每个对话最大数量，每个剧本最大数量
        let map = new Map<string, BarrageReturn[]>(); // index => BarrageReturn[]
        for(let barrage of result) {
            let { index } = barrage;
            if(!map.has(index)) {
                map.set(index, []);
            }
            map.get(index).push(new BarrageReturn(barrage));
        }
        let ratio = result.length > max? max/result.length: 1;

        let barrageList: BarrageReturn[] = [];
        for(let [_, barrages] of map) {
            let count = Math.ceil(barrages.length * ratio);
            if(count > perMax) count = perMax;
            
            let curBarrages = getRandEelm(barrages, count);
            barrageList = barrageList.concat(curBarrages);
        }
        return resResult(STATUS.SUCCESS, { barrageList });
    }
}