/**
 * Created by rockyl on 2019-05-08.
 *
 * 文本轮播
 */

import ScillaComponent from "components/base/ScillaComponent";
import {createTween, ease, Entity} from "scilla";
import Transform from "components/base/Transform";
import TextRenderer from "components/renderer/TextRenderer";

export enum DIR {
	UP,
	DOWN,
}

export default class LabelCarousel extends ScillaComponent {
	entity0: Entity;
	entity1: Entity;
	offset = 40;
	interval = 1000;
	scrollDuration = 500;
	dir: DIR = DIR.UP;
	getTextFunc: Function;
	autoPlay = false;

	_playing = false;

	private _index = 0;
	private _labels = [];
	private _timer;

	onAwake() {
		super.onAwake();

		const {_labels, entity0, entity1, offset, dir} = this;
		const entities = [entity0, entity1];
		for (let entity of entities) {
			let transform = entity.getComponent(Transform);
			let textRenderer = entity.getComponent(TextRenderer);

			transform.position.y = offset * (dir === DIR.UP ? -1 : 1);
			transform.alpha = 0;

			_labels.push({
				transform,
				textRenderer
			});
		}

		if(this.autoPlay){
			this.play();
		}
	}

	play() {
		this.playNext();

		this.stop();
		this._timer = setInterval(() => {
			this.playNext();
		}, this.interval);
		this._playing = true;
	}

	stop() {
		if(this._timer){
			clearInterval(this._timer);
			this._timer = null;
		}
		this._playing = false;
	}

	private updateText(textRenderer){
		let text = this.getTextFunc ? this.getTextFunc() : null;
		if(text){
			textRenderer.text = text;
		}
	}

	playNext() {
		const {_labels, _index, scrollDuration, offset, dir} = this;

		let nextLabel = _labels[_index % 2];

		const sign = dir === DIR.UP ? -1 : 1;

		this.updateText(nextLabel.textRenderer);
		createTween(this, nextLabel.transform, true)
			.set({position: {y: offset * sign * -1}})
			.to({position: {y: 0}, alpha: 1}, scrollDuration, ease.cubicOut);

		if (_index > 0) {
			let lastLabel = _labels[(_index + 1) % 2];
			createTween(this, lastLabel.transform, true)
				.to({position: {y: offset * sign}, alpha: 0}, scrollDuration, ease.cubicOut);
		}

		this._index++;
	}
}
