/**
 * Created by rockyl on 2019-04-10.
 *
 * 警告对话框内容
 */

import DialogContent from "../popup/DialogContent";
import {dynamic, Entity, resource} from "scilla";
import TextRenderer from "components/renderer/TextRenderer";
import {stringFixed} from "../game/utils";

export default class PKMatching extends DialogContent {
	Title: Entity;
	SelfName: Entity;
	OtherName: Entity;
	AvatarOther: Entity;
	AvatarWaiting: Entity;
	CloseButton: Entity;

	userNickname: dynamic;
	otherName: dynamic;

	private _titleRenderer: TextRenderer;
	private _selfNameRenderer: TextRenderer;
	private _otherNameRenderer: TextRenderer;
	private _timer;

	onCreate() {
		super.onCreate();

		this._titleRenderer = this.Title.getComponent(TextRenderer);
		this._selfNameRenderer = this.SelfName.getComponent(TextRenderer);
		this._otherNameRenderer = this.OtherName.getComponent(TextRenderer);
	}

	setup(data: any) {
		const {channel} = data;

		this._titleRenderer.text = '正在匹配对手…';
		this._selfNameRenderer.text = stringFixed(this.userNickname);
		this._otherNameRenderer.text = stringFixed(this.otherName);

		this.AvatarOther.enabled = false;
		this.AvatarWaiting.enabled = true;
		this.CloseButton.enabled = false;

		this.stop();
		if(channel === 1){
			this.onMatched();
		}else{
			this._timer = setTimeout(this.onMatched, Math.random() * 2000 + 2000);
		}
	}

	stop() {
		if (this._timer) {
			clearTimeout(this._timer);
			this._timer = null;
		}
	}

	protected onTapCloseButton() {
		super.onTapCloseButton();

		this.stop();
	}

	private onMatched = () => {
		this._titleRenderer.text = '匹配成功';

		this.AvatarOther.enabled = true;
		this.AvatarWaiting.enabled = false;
		//this.CloseButton.enabled = false;

		setTimeout(this.hide, 1000, 'success');
	}
}
