/**
 * Created by rockyl on 2020-02-03.
 */
import {props} from "../props";
import {Turntable} from "./Turntable";

export class BreakUpPart extends engine.Container {
	private _body: engine.Image;

	private _turntable: Turntable;
	private _from;
	private _to;
	private _fromR;
	private _toR;

	constructor(turntable: Turntable, from, to) {
		super();

		let body = this._body = new engine.Image();
		this.addChild(body);

		let mask = this._body.mask = new engine.Graphics();
		this.addChild(mask);

		this._turntable = turntable;
		this._from = from;
		this._to = to;
		this._fromR = from * Math.PI / 180;
		this._toR = to * Math.PI / 180;
	}

	updateMask() {
		let mask = this._body.mask;
		mask.beginFill(0xff0000);
		mask.moveTo(0, 0);
		mask.arc(0, 0, this._turntable.radius + 5, this._fromR, this._toR);
		mask.endFill();

		let [min, max] = props.breakUpDistanceRange;
		let mid = (this._toR - this._fromR) / 2 + this._fromR;
		this.x = Math.cos(mid) * Math.random() * max + min;
		this.y = Math.sin(mid) * Math.random() * max + min;

		this.alpha = 1;
		this.rotation = 0;
	}

	playFall(rotation) {
		this._body.rotation = rotation;
		return new Promise(resolve => {
			let angle = (this._to - this._from) / 2 + this._from;
			let rotation = (angle > 270 ? 360 : 0) + 90 - angle;
			engine.Tween.get(this, null, null, true)
				.to({y: this.y + props.turntableFallDistance, alpha: 0, rotation}, props.turntableFallDuration, engine.Ease.cubicIn)
				.call(resolve)
		})
	}

	get body() {
		return this._body;
	}
}
