import { GameConfig } from "../../config/GameConfig";
import { SocialModuleC } from "./SocialModuleC";
import { DSModuleS } from "../DSEvent/DSModule";

/**
 * Social模块Server端
 */
export class SocialModuleS extends DSModuleS<SocialModuleC, null> {  

	protected onStart(): void {
		super.onStart(); // 必须调用
	}

	@Decorator.noReply()
	net_locBarrage(uid: string, name: string, msg: string, type: number = 0) {
		const allPlayer = Player.getAllPlayers();
		for (const player of allPlayer) {
			if (player?.userId == uid)
				continue;
			this.getClient(player)?.net_receiveBarrage(name, msg, type);
		}
	}
	protected onUpdate(dt: number): void {
		this.updateBarrage(dt);
	}

	@Decorator.noReply()
	public net_allBarrage(uid: string, name: string, msg: string, type: number = 0) {
		let info = {
			uid: uid,
			type: type,
			name: name,
			txt: msg
		}
		this.sendMsg(2, JSON.stringify(info));
	}

	/******************** 弹幕 **********************/
	public onBecomeHost(): void {
		this.initBarrage();
	}
	public onCancelHost(): void {
		this.dtTime = -1;
	}
	public onMsg(type: number, data: string): void {
		let info = JSON.parse(data);
		switch (type) {
			case 1://机器人弹幕
				this.getAllClient().net_robotBarrage(info.ndx, info.bid);
				break;
			case 2://玩家弹幕
				this.net_locBarrage(info.uid, info.name, info.txt, info.type)
				break;
		}
	}


	private nameList: string[] = [];
	private idList: number[] = [];
	private dtTime: number = -1;
	public initBarrage() {
		if (this.idList.length < 1) {
			let cfgs = GameConfig.Barrage.getAllElement();
			for (const cfg of cfgs) {
				if (cfg.nickName)
					this.nameList.push(cfg.nickName);
				this.idList.push(cfg.id);
			}
		}
		this.dtTime = 10;
	}
	public updateBarrage(dt: number) {
		if (this.dtTime < 0)
			return;
		this.dtTime -= dt;
		if (this.dtTime <= 0) {
			this.sendBarrage();
		}
	}
	private sendBarrage() {
		this.dtTime = 10;
		let idx = MathUtil.randomInt(0, this.idList.length);
		let id = this.idList[idx];
		let cfg = GameConfig.Barrage.getElement(id);
		if (!cfg)
			return;
		let rn = MathUtil.randomInt(0, this.nameList.length);
		let info = {
			type: cfg.type,
			ndx: rn,
			bid: id,
		}
		this.sendMsg(1, JSON.stringify(info));
		if (cfg.randTime.length > 1)
			this.dtTime = MathUtil.randomInt(cfg.randTime[0], cfg.randTime[1]);
		else if (cfg.randTime.length == 1)
			this.dtTime = cfg.randTime[0];
	}

}
