// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { asyncDelay, RandomInt, showFireworks } from "../common/utils";

var effect = cc.Class({
	extends: cc.Component,

	properties: {
	},

	ctor: function () {
		effect.inst = this;
		OP26.effect = effect;
	},

	showEffect: function () {
		const bg = cc.find('Canvas/bg/connent');

		this.showAllFirework(bg, cc.find('paperBase').children);
		OP26.speaker.inst.play_congratulation();
	},

	showEffect2: function () {
		const bg = cc.find('Canvas/bg/connent');

		showFireworks(bg, cc.find('RibbonNodeBase').children, cc.v2(0, -400), cc.v2(0, 1000), 200, 200
		);
		showFireworks(bg, cc.find('RibbonNodeBase').children, cc.v2(-600, -400), cc.v2(200, 1000), 200, 200
		);
		showFireworks(bg, cc.find('RibbonNodeBase').children, cc.v2(600, -400), cc.v2(-200, 1000), 200, 200
		);
	},

	async showOneFirework(pos, parentNode, nodeList) {
		for (let i = 0; i < 3; i++) {
			this.showFirework(pos, parentNode, nodeList, 200, 200, 15);
			await asyncDelay(0.1);
		}
	},

	async showAllFirework(parentNode, nodeList) {
		for (let i = 0; i < 6; i++) {
			this.showFirework(cc.v2(0, -parentNode.height / 2), parentNode, nodeList, parentNode.width * 2 / 3, parentNode.height * 1.3);
			await asyncDelay(0.1);
		}
	},

	showFirework(pos, parentNode, nodeList, width = 200, height = 200, number = 30) {
		for (let i = 0; i < number; i++) {
			const quad = this.createQuads(pos, parentNode, nodeList);
			const targetX = RandomInt(width / 2, -width / 2);
			const targetY = RandomInt(height);

			cc.tween(quad)
				.by(0.5, { x: targetX })
				.by(3, { x: targetX * 2 })
				.start();

			cc.tween(quad)
				.by(0.5, { y: targetY }, { easing: 'quadOut' })
				.to(4, { y: -parentNode.height * 2 }, { easing: 'quadIn' })
				.removeSelf()
				.start();

			cc.tween(quad)
				.delay(1)
				.to(1.5, { opacity: 0 })
				.start();
		}
	},

	createQuads(pos, parentNode, nodeList) {
		const quadBase = cc.instantiate(nodeList[RandomInt(nodeList.length)]);
		quadBase.x = pos.x;
		quadBase.y = pos.y;
		quadBase.z = pos.z;
		quadBase.angle = RandomInt(180);
		quadBase.parent = parentNode;

		const quad = quadBase.getChildByName('quad');
		quad.x = 0;
		quad.y = 0;
		quad.angle = RandomInt(180);

		const paper = quad.getChildByName('paper');
		paper.scaleX = Math.random() * 0.5 + 0.5;
		paper.scaleY = Math.random() * 0.5 + 0.5;

		quadBase.scaleX = Math.random();
		cc.tween(quadBase)
			.to((1 - quadBase.scaleX) * 0.3, { scaleX: 1 })
			.call(() => {
				const time = Math.random() * 0.2;
				cc.tween(quadBase)
					.to(0.1 + time, { scaleX: -1 })
					.to(0.1 + time, { scaleX: 1 })
					.union()
					.repeatForever()
					.start();
			})
			.start();


		return quadBase;
	},
});
