/**
 * Created by rockyl on 2018/8/17.
 * 障碍块
 */

import {getBlockAsset} from "./utils";
import {props} from "../props";

export default class Block extends engine.Container {
	private body: svga.Svga;

	type;
	dir;

	constructor() {
		super();

		let body = this.body = new svga.Svga();
		body.x = -props.blockWidth / 2;
		body.y = -props.blockHitHeight - props.blockPaddingTop;
		this.addChild(body);
	}

	reset({type,}) {
		this.dir = Math.random() > 0.5 ? 1 : -1;

		if (this.type != type) {
			this.type = type;

			let asset = getBlockAsset(type);
			this.body.source = 'asset://' + asset.uuid;
		}
		this.scaleX = this.dir;
		this.body.gotoAndStop(1);
	}

	playEnter(index, animation) {
		this.visible = true;
		this.x = this.dir * this.stage.width;
		const [min, max] = props.blockDurationRange;
		let duration = Math.max(max - index * props.blockDurationStep, min);
		duration = duration + max * Math.random() * props.blockDurationRandom * (Math.random() > 0.5 ? 1 : -1);
		return new Promise(resolve => {
			if (animation) {
				engine.Tween.get(this, null, null, true)
					.to({x: 0,}, duration)
					.call(resolve);
			} else {
				this.x = 0;
				setTimeout(() => {
					console.log(this.body);
				}, 200);
				resolve();
			}
		})
	}

	playLeave() {
		this.visible = false;
	}

	playEffect() {
		let body = this.body;
		body.play(true, false);
		body.once(engine.Event.END_FRAME, function () {
			body.gotoAndStop(1);
		}, this);
	}

	stop() {
		engine.Tween.removeTweens(this);
	}
}
