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

import {getBlockAsset,getBlockHitAsset,getTextureByName} from "./utils";
import {props} from "../props";

export default class Block extends engine.Container {
	private body: svga.Svga;
	private bodyHit: svga.Svga;
	private bodyProfect: 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);

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

		console.log("props.blockProfectOffset",props.blockProfectOffset)

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

		
	}

	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;

			
			let assetHit = getBlockHitAsset(type);
			console.log("assetHit",assetHit)
			this.bodyHit.source = 'asset://' + assetHit.uuid;
		}

		this.bodyProfect.source = 'asset://' + engine.getAssetByName("完美方块素材").uuid;

		this.scaleX = this.dir;
		this.body.gotoAndStop(1);
		this.bodyHit.gotoAndStop(1);
		this.bodyProfect.gotoAndStop(1);

		this.body.visible=true;
		this.bodyHit.visible=false;
	}

	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);
	}

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

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

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