import ScillaComponent from "scilla-components/src/base/ScillaComponent";
import { Entity, instantiate, resource, dynamic } from "scilla/src";
import { setText } from "../entityUtils";
import { getTween } from "../getTween";
import { alien } from "../navigator/StackNavigator";
import { INavigatorViewBase } from "../navigator/VirtualNavigator";
import { setScale } from "../transformUtils";

export default class ScenePlay extends ScillaComponent implements INavigatorViewBase {
	doJoin: dynamic;

	iconResource: resource;
	countTxt: Entity;
	num1: Entity;
	num2: Entity;
	num3: Entity;
	box1: Entity;
	box2: Entity;
	box3: Entity;
	private COUNT_DOWN_SEC = window['COUNT_DOWN_SEC'];
	private _startTag = false;
	private _msPassed = 0;
	private _ballCounter = 0;
	// private _timeoutTag: boolean;
	onAwake() {
		super.onAwake();

		this.showBox1();
		this.initText();
		this.play321Countdown();

		let addCounter = 0;
		const add = () => {
			addCounter++;
			this.addBall();
		}

		setInterval(() => {
			console.log('上一秒摇晃的能量是', addCounter);
			addCounter = 0;
		}, 1000);

		//运动事件监听
		if (window['DeviceMotionEvent']) {
			window.addEventListener('devicemotion', deviceMotionHandler, false);
		}

		var SHAKE_THRESHOLD = 50; //累积200的速度值出一个球
		var x, y, z, last_x = 0, last_y = 0, last_z = 0;
		var speedCounter = 0;
		var _this = this;
		function deviceMotionHandler(eventData) {
			if (!_this._startTag) return;
			var acceleration = eventData.accelerationIncludingGravity;

			x = acceleration.x;
			y = acceleration.y;
			z = acceleration.z;
			var speed = Math.abs(x + y + z - last_x - last_y - last_z) * 1;
			//快的时候差不多速度几十
			//静止的时候是0
			speedCounter += speed;
			if (speedCounter >= SHAKE_THRESHOLD) {
				speedCounter = 0;
				add();
			}
			last_x = x;
			last_y = y;
			last_z = z;
		}

		this._startTag = false;
	}

	async wait(ms) {
		return new Promise((r) => {
			setTimeout(r, ms);
		})
	}
	async play321Countdown() {
		setScale(this.num1, 3);
		setScale(this.num2, 3);
		setScale(this.num3, 3);
		this.num1.enabled = false;
		this.num2.enabled = false;
		this.num3.enabled = true;
		await getTween(this, this.num3, { scalex: 1, scaley: 1 }, 300);
		await this.wait(600);
		this.num3.enabled = false;
		this.num2.enabled = true;
		await getTween(this, this.num2, { scalex: 1, scaley: 1 }, 300);
		await this.wait(600);
		this.num2.enabled = false;
		this.num1.enabled = true;
		await getTween(this, this.num1, { scalex: 1, scaley: 1 }, 300);
		await this.wait(600);
		this.num1.enabled = false;
		this.startRealCountdown();
	}

	startRealCountdown() {
		this._startTag = true;
		this._msPassed = 0;
		this._lastTimer = Date.now();
		this._ballCounter = 0;
	}

	private _lastTimer: number;
	onUpdate() {
		if (!this._startTag) return;
		this._msPassed += (Date.now() - this._lastTimer);
		const left = this.COUNT_DOWN_SEC * 1000 - this._msPassed;
		// console.log(left)
		const mPassed = Math.floor(left / 1000);
		let msPassed = left % 1000;
		msPassed = Math.floor(msPassed / 10);
		this.updateText(mPassed, msPassed);
		this._lastTimer = Date.now();
		if (left <= 0) {
			this.updateText(0, 0);
			this._startTag = false;
			this.onTimerout();
		}
	}

	onTimerout() {
		console.log('onTimerout');
		this.broadcast('callApi', 1, 'activitySubmit', {
			weddingId: window['CFG'].weddingId,
			activityId: window['CFG'].activityId,
			orderId: this.doJoin.orderId,
			score: this._ballCounter
		});
	}

	onRespone_activitySubmit() {
		this.bubbling('showDialog', 'Score', this._ballCounter);
	}

	onError_activitySubmit(error) {
		this.bubbling('showDialog', 'Alert', '网络异常，请稍后再试~');
	}


	getNumber(num) {
		if (num < 10)
			return `0${num}`
		return `${num}`
	}

	updateText(a, b) {
		setText(this.countTxt, `${this.getNumber(a)}.${this.getNumber(b)}s`)
	}

	initText() {
		setText(this.countTxt, `${this.getNumber(this.COUNT_DOWN_SEC)}.00s`)
	}

	private _balllist: any[] = [];
	addBall() {
		this._ballCounter++;
		const iocn = instantiate(this.iconResource);
		this.entity.addChild(iocn);
		this._balllist.push(iocn);

		if (this._ballCounter > 100 / (16 / this.COUNT_DOWN_SEC)) {
			this.showBox3();
		} else if (this._ballCounter > 50 / (16 / this.COUNT_DOWN_SEC)) {
			this.showBox2();
		} else {
			this.showBox1();
		}
	}

	showBox1() {
		this.box1.enabled = true;
		this.box2.enabled = false;
		this.box3.enabled = false;
	}
	showBox2() {
		this.box1.enabled = false;
		this.box2.enabled = true;
		this.box3.enabled = false;
	}
	showBox3() {
		this.box1.enabled = false;
		this.box2.enabled = false;
		this.box3.enabled = true;
	}

	// onGameOver() {
	// 	this.bubbling('fuck', 'result');
	// }

	// _timer
	onDidEnter(last: string, action: alien.NavigatorAction, parameters: any): void {
		this.entity.enabled = true;
	}

	onDidLeave(next: string, action: alien.NavigatorAction, parameters: any): void {
		this._balllist.forEach(iocn => this.entity.removeChild(iocn));
		this._balllist = [];
		this.entity.enabled = false;
	}

	async onWillEnter(last: string, action: alien.NavigatorAction, parameters: any) {
	}

	async onWillLeave(next: string, action: alien.NavigatorAction, parameters: any) {
	}

	onWillMount(last: string, action: alien.NavigatorAction, parameters: any): Promise<any> {
		return undefined;
	}

	onWillUnMount(next: string, action: alien.NavigatorAction, parameters: any): Promise<any> {
		return undefined;
	}

}
