/**
 * Created by rockyl on 2019-05-14.
 *
 * pk结果一侧
 */

import ScillaComponent from "components/base/ScillaComponent";
import {createTween, ease, engine, Entity, resource} from "scilla";
import Transform from "components/base/Transform";
import TextRenderer from "components/renderer/TextRenderer";
import RunNumber from "../common/RunNumber";
import {renderRunCredits, stringFixed} from "./utils";
import Zoom from "components/animation/Zoom";
import TextureRenderer from "components/renderer/TextureRenderer";

export default class PKResultSide extends ScillaComponent {
	LabelName: Entity;
	LabelCredits: Entity;
	ResultTag: Entity;
	Body: Entity;
	Stars: Entity;
	side: number;
	winTagRes: resource;
	loseTagRes: resource;
	equalTagRes: resource;
	winBodyRes: resource;
	loseBodyRes: resource;

	private _labelName: TextRenderer;
	private _labelCredits: TextRenderer;
	private _labelCreditsTransform: Transform;
	private _resultTagZoom: Zoom;
	private _resultTagRenderer: TextureRenderer;
	private _bodyRenderer: TextureRenderer;
	private _labelRunCredits: RunNumber;

	private _pos;

	onCreate() {
		super.onCreate();

		this._labelName = this.LabelName.getComponent(TextRenderer);
		this._labelCredits = this.LabelCredits.getComponent(TextRenderer);
		this._labelCreditsTransform = this.LabelCredits.getComponent(Transform);
		this._resultTagRenderer = this.ResultTag.getComponent(TextureRenderer);
		this._bodyRenderer = this.Body.getComponent(TextureRenderer);
		this._resultTagZoom = this.ResultTag.getComponent(Zoom);
		this._labelRunCredits = this.LabelCredits.getComponent(RunNumber);

		this._labelRunCredits.$renderFunc = renderRunCredits;

		this._pos = this.transform.position.x;
	}

	onUpdate(t) {
		super.onUpdate(t);
	}

	async play(data) {
		const {nickname, finalCredits, otherFinalCredits, resultState} = data;

		this._labelName.text = stringFixed(nickname);
		this._labelCredits.text = renderRunCredits(finalCredits);

		const win = resultState === this.side;
		this._bodyRenderer.texture = resultState === 0 || win ? this.winBodyRes : this.loseBodyRes;

		this.ResultTag.enabled = false;
		this.Stars.enabled = false;

		const stageWidth = engine.renderContext.stageSize.width;
		await createTween(this, this.transform.position)
			.set({x: stageWidth * this.side}, true)
			.to({x: this._pos}, 300, ease.cubicOut)
			.getPromise();

		this._labelCreditsTransform.scale.setXY(1, 1);

		this._resultTagRenderer.texture = resultState === 0 ? this.equalTagRes : (win ? this.winTagRes : this.loseTagRes);

		setTimeout(() => {
			this.ResultTag.enabled = true;
			if(win){
				this.Stars.enabled = true;
			}
		}, 300);

		if (resultState === 0) {

		} else {
			const toValue = win ? finalCredits + otherFinalCredits : 0;

			await createTween(this, this._labelCreditsTransform)
				.wait(1000)
				.call(() => {
					this._labelRunCredits.play(toValue);
				})
				.to({scale: win ? {x: 1.4, y: 1.4} : {x: 0.6, y: 0.6}}, 1000)
				.getPromise();
		}

	}
}
