import {PoolElement} from "../Component/Pool";
import MoveObjcet from "./MoveObject";
import {MConst} from "../Global/MConst";
import GameObject from "./GameObject";
import Collider, {CircleCollider, ColliderGroup, PointCollider} from "../Phycics/Collider";
import Game from "./Game";
import {DataMgr} from "../Mgr/DataMgr";
import MTimer from "../Global/MTimer";
import GameMgr from "../Mgr/GameMgr";
import {getTexture} from "../utils";

const bulletSpeedValue = 20;
/**顾名思义 */
const frameCountThatBulletsMoveInX = 4;

export default class Bullet extends MoveObjcet implements PoolElement {
	public power: number = 1;

	constructor() {
		super();
		this.addChild(new engine.Image(getTexture("09bdff41-2fe3-4298-ad3a-1d2eaf6af778")));

		let collider = this.addComponent(PointCollider) as PointCollider;
		collider.group = ColliderGroup.Bullet;
		collider.setData(2, 0);
		this.physics.velocity.y = -bulletSpeedValue;
	}

	init(power: number) {
		this.power = power;
		return this;
	}

	onElementInit() {
		this.enableAllComponents();
		this.visible = true;
	}

	onElementRecycle() {
		this.disableAllComponents();
		this.visible = false;
	}

	onCollisionEnter(other: Collider) {
		if (other.group == ColliderGroup.Ball || other.group == ColliderGroup.Top) {
			DataMgr.game._pool.bullet.recycle(this);
		}
	}
}

export class BulletGroup {
	private moveDatas: { bullet: Bullet, frameOffset: number }[] = [];
	public restFrameCountThatBulletsMoveInX: number = frameCountThatBulletsMoveInX;

	constructor(position: engine.Point, rowBulletNum: number) {
		for (let i = 0; i < rowBulletNum; i++) {
			const bullet = DataMgr.game._pool.bullet.spwan().init(Math.floor(DataMgr.game.powerScore / 100));
			bullet.x = position.x - bullet.width / 2;
			bullet.y = position.y + bullet.height / 2;
			let frameOffset = ((i - (rowBulletNum - 1) / 2) * (bullet.width + 3)) / frameCountThatBulletsMoveInX;
			this.moveDatas.push({
				bullet: bullet,
				frameOffset,
			});
		}

		DataMgr.game._horizontalMoveMgr.movingList.push(this);
	}

	public onUpdate() {
		let data: { bullet: Bullet, frameOffset: number } = null;
		for (let i = 0; i < this.moveDatas.length; i++) {
			data = this.moveDatas[i];
			data.bullet.x += data.frameOffset;
		}
		this.restFrameCountThatBulletsMoveInX--;
	}
}

export class HorizontalMoveMgr extends GameMgr {
	constructor() {
		super("HorizontalMoveMgr")
	}

	public movingList: BulletGroup[] = [];

	protected onUpdate() {
		if (this.pause) return;
		for (let i = 0; i < this.movingList.length; i++) {
			this.movingList[i].onUpdate();
		}

		this.movingList = this.movingList.filter(e => e.restFrameCountThatBulletsMoveInX > 0);
	}
}