import Ball from "./Ball";
import BallRaycast from "./BallRaycast";
import Brick from "./Brick";
import Game from "./Game";
import Global, { PROP_TYPE } from "./Global";
import { PoolManager, PoolType } from "./PoolManager";
import Prop from "./Prop";
import SoundManager from "./SoundManager";
import Userdata from "./Userdata";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Playground extends cc.Component {
	private static readonly MIN_DEGREE = 7;
	private static readonly MAX_DEGREE = 173;
	private static readonly WIDHT = 690;
	public static instance: Playground = null;

	@property(BallRaycast)
	ballAimLine: BallRaycast = null;

	@property(cc.Node)
	ballMarkNode: cc.Node = null;

	@property(cc.Node)
	bricksRootNode: cc.Node = null;
	@property(cc.Node)
	ballsRootNode: cc.Node = null;
	@property(cc.Node)
	propsRootNode: cc.Node = null;

	@property(cc.Node)
	fingerNode: cc.Node = null;

	@property(cc.Node)
	boardNode: cc.Node = null;

	@property(cc.Node)
	wallNode: cc.Node = null;

	@property(sp.Skeleton)
	startSkeleton: sp.Skeleton = null;

	@property(cc.Node)
	buttonShootNode: cc.Node = null;

	@property(cc.Node)
	buttonTimesNode: cc.Node = null;

	@property(cc.Node)
	buttonWallNode: cc.Node = null;

	private touchId = -1;
	private isFired = false;
	private startTouch: cc.Vec2;
	private _zeroAngleVec = cc.v2(1, 0).normalizeSelf();
	private fireDirection: cc.Vec2;
	private ballSpriteFrame: cc.SpriteFrame = null;

	private currBalls: Ball[] = [];
	private breakableBricks: Brick[] = [];
	private obstacleBricks: Brick[] = [];
	private boardStartPos: cc.Vec2;
	private boardMoveWidth = 0;
	private recycleBrickCounter = 0;
	private createPropTimes = 0;

	onLoad() {
		Playground.instance = this;

		this.boardMoveWidth = (Playground.WIDHT) * 0.5;// - this.boardNode.width;

		this.openPhysics();

		// 使用枚举类型来注册
		this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
		this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
		this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
		this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
	}

	onEnable() {
		this.loadSkin();
		this.loadLevel(Userdata.SelectLevel);
	}

	resetLevel() {
		cc.director.getPhysicsManager().enabled = true;
		this.isFired = false;
		this.recycleBrickCounter = 0;
		this.createPropTimes = 0;

		this.ballMarkNode.active = true;
		this.ballAimLine.node.active = false;
		this.boardNode.position = cc.v2(0, this.boardNode.position.y);

		this.wallNode.active = false;

		this.clearBricks();
		this.clearBalls();
		this.clearProps();
	}

	loadLevel(levelNum: number, cb?: Function) {
		this.resetLevel();

		let loadNum = levelNum > 1161 ? (((levelNum - 1161) % 1000) + 150) : levelNum;
		cc.loader.loadRes('d/' + loadNum, (err, data) => {
			if (data && data.json) {
				cc.log('data = ', data.json);

				this.createLevel(data.json.data, cb);
			}
		});
	}

	private createLevel(data, cb?: Function) {
		this.bricksRootNode.removeAllChildren();
		Game.instance.updateLevelNum();

		let width = Math.max(data[0], data[1]);
		let brickOriginWidth = Playground.WIDHT / width;
		let brickWidth = brickOriginWidth * 0.76;
		let brickPhysicWidth = brickOriginWidth * 0.76;

		let startPos = cc.v2((1 - width) * 0.5 * brickOriginWidth, (1 - width) * 0.5 * brickOriginWidth);

		//bricks config
		for (let i = 2, len = data.length; i < len; i += 4) {
			let x = data[i];
			let y = data[i + 1];
			let isObstacle = data[i + 2];
			let colorValue = data[i + 3];

			let _brick = this.createBrick();
			_brick.init(isObstacle, isObstacle ? cc.color().fromHEX('#828282') : cc.color(colorValue.toString(16))
				, brickWidth, isObstacle ? brickPhysicWidth : brickPhysicWidth);
			_brick.node.position = startPos.add(cc.v2(x * brickOriginWidth, y * brickOriginWidth));

			if (!isObstacle) {
				this.breakableBricks.push(_brick);
			} else {
				this.obstacleBricks.push(_brick);
			}
		}

		cb && cb();
		this.onLevelLoaded();
	}

	onLevelLoaded() {
		let loading = cc.find('Loading');
		if (loading) {
			cc.game.removePersistRootNode(loading);
			loading.destroy();
		}

		cc.log('total bricks -> ' + this.breakableBricks.length);
		this.recycleBrickCounter = 0;
		this.createPropTimes = 0;
		this.showFingerAnimation();

		SoundManager.playStartAudio();

		this.startSkeleton.setAnimation(0, 'animation', false);
	}


	loadSkin() {
		//加载图片皮肤，并设置尺寸
		cc.loader.loadRes('skins/skin_' + Userdata.CurrSkin, cc.SpriteFrame, (err, res) => {
			this.ballSpriteFrame = res;
			this.ballMarkNode.getComponent(cc.Sprite).spriteFrame = res;
		});
	}

	//物理设置
	openPhysics() {
		cc.director.getPhysicsManager().enabled = true;
		cc.director.getPhysicsManager().gravity = cc.v2(0, 0);//-8000);

		console.log('os = ', cc.sys.os);
		if (cc.sys.os == cc.sys.OS_IOS) {

			var manager = cc.director.getPhysicsManager();
			// 开启物理步长的设置
			manager.enabledAccumulator = true;

			// manager.PTM_RATIO = 6;

			// manager.MAX_ACCUMULATOR = 

			// 物理步长，默认 FIXED_TIME_STEP 是 1/60
			manager.FIXED_TIME_STEP = 1 / 3;

			// 每次更新物理系统处理速度的迭代次数，默认为 10
			manager.VELOCITY_ITERATIONS = 5;

			// 每次更新物理系统处理位置的迭代次数，默认为 10
			manager.POSITION_ITERATIONS = 5;
		}

		if (Global.DEBUG) {
			console.log('physics in debug mode.');
			cc.director.getPhysicsManager().debugDrawFlags =
				// cc.PhysicsManager.DrawBits.e_aabbBit |
				//cc.PhysicsManager.DrawBits.e_pairBit |
				//cc.PhysicsManager.DrawBits.e_jointBit |
				cc.PhysicsManager.DrawBits.e_shapeBit
				;
		} else {
			console.log('physics not in debug.');
			cc.director.getPhysicsManager().debugDrawFlags = 0;
		}
	}


	onTouchStart(event: cc.Event.EventTouch) {
		this.touchId = event.getID();
		if (this.isFired) {//木板左右移动
			this.boardStartPos = this.boardNode.position;
		} else {//显示发射线
			this.startAim();
			this.onTouchMove(event);
		}
	}

	onTouchMove(event: cc.Event.EventTouch) {
		if (this.isFired) {
			let x = this.boardStartPos.x + event.getLocationX() - event.getStartLocation().x;
			if (x < -this.boardMoveWidth) {
				x = -this.boardMoveWidth;
			} else if (x > this.boardMoveWidth) {
				x = this.boardMoveWidth;
			}

			this.boardNode.position = cc.v2(x, this.boardStartPos.y);
		} else {//draw line to aim
			if (this.touchId != event.getID()) {
				return;
			}

			let currTouch = event.touch.getLocation();
			if (currTouch.y < this.startTouch.y) {
				currTouch.y = this.startTouch.y + (this.startTouch.y - currTouch.y);
			}

			let direction = cc.v2(currTouch.x - this.startTouch.x, currTouch.y - this.startTouch.y).normalizeSelf();

			let _angle = direction.angle(this._zeroAngleVec);
			let _degree = cc.misc.radiansToDegrees(_angle);
			if (_degree < Playground.MIN_DEGREE || _degree > Playground.MAX_DEGREE) {
				_angle = cc.misc.degreesToRadians(_degree < Playground.MIN_DEGREE ? Playground.MIN_DEGREE : Playground.MAX_DEGREE);
				direction = cc.v2(Math.cos(_angle), Math.sin(_angle)).normalize();
			}

			this.aim(direction);
		}
	}


	onTouchEnd(event: cc.Event.EventTouch) {
		if (this.isFired) {

		} else {
			this.tryFire();
		}
	}

	onTouchCancel(event: cc.Event.EventTouch) {
		this.cancelAim();
	}

	showFingerAnimation() {
		this.fingerNode.active = true;
		this.fingerNode.stopAllActions();
		this.fingerNode.position = cc.v2(-200, -50);
		this.fingerNode.scale = 1.2;
		this.fingerNode.runAction(
			cc.repeatForever(
				cc.sequence(
					cc.scaleTo(0.3, 0.8),
					cc.moveBy(1, cc.v2(450, 0)),
					cc.moveBy(1, cc.v2(-450, 0)),
					cc.scaleTo(0.5, 1.2)
				)
			)
		);
	}

	startAim() {
		// Game.instance.fingerNode.active = false;
		this.startTouch = this.ballMarkNode.convertToWorldSpaceAR(cc.v2());
		cc.log("ballMarkNode start = " + this.ballMarkNode.position.x + ", " + this.ballMarkNode.position.y);

		if (!this.isFired) {
			this.fingerNode.active = false;
		}
	}

	aim(direction: cc.Vec2) {
		this.fireDirection = direction;

		this.ballAimLine.node.active = true;
		this.ballAimLine.startRaycast(this.startTouch, this.fireDirection, 13);
	}

	cancelAim() {
		if (!this.isFired) {
			this.ballAimLine.node.active = false;
			this.showFingerAnimation();
		}
	}

	tryFire() {
		if (this.isFired)
			return;

		if (this.ballAimLine.node.active) {//Fire
			this.isFired = true;
			this.ballMarkNode.active = false;
			this.ballAimLine.node.active = false;

			let worldPos = this.ballMarkNode.convertToWorldSpaceAR(cc.Vec2.ZERO);
			let pos = this.node.convertToNodeSpaceAR(worldPos);
			this.fireBall(pos, this.fireDirection);

			Game.instance.IsStartGame = true;
		}
	}

	createBall(): Ball {
		let _ball = PoolManager.Ins.get(PoolType.BALL, this);

		_ball.parent = this.ballsRootNode;
		_ball.active = true;

		let ball = _ball.getComponent(Ball);
		ball.updateSkin(this.ballSpriteFrame);

		return ball;
	}

	createBrick(): Brick {
		let _brick = PoolManager.Ins.get(PoolType.BRICK, this);

		_brick.parent = this.bricksRootNode;
		_brick.active = true;

		return _brick.getComponent(Brick);
	}

	createProp(propType: PROP_TYPE): Prop {
		let _node: cc.Node = null;

		if (propType == PROP_TYPE.SHOOT3) {
			_node = PoolManager.Ins.get(PoolType.PROP_SHOOT, this);
		} else if (propType == PROP_TYPE.TIMES3) {
			_node = PoolManager.Ins.get(PoolType.PROP_TIMES, this);
		} else if (propType == PROP_TYPE.WALL) {
			_node = PoolManager.Ins.get(PoolType.PROP_WALL, this);
		}

		_node.parent = this.propsRootNode;
		_node.active = true;

		let prop = _node.getComponent(Prop);
		return prop;
	}

	pickupProp(propType: number) {
		cc.log('pickup proptype = ' + propType);
		SoundManager.playProp();
		if (propType == PROP_TYPE.SHOOT3) {
			let worldPos = this.ballMarkNode.convertToWorldSpaceAR(cc.Vec2.ZERO);
			let pos = this.node.convertToNodeSpaceAR(worldPos);
			let leftDir = cc.v2(-1, 1).normalizeSelf();
			this.fireBall(pos, leftDir);
			let topDir = cc.v2(0, 1).normalizeSelf();
			this.fireBall(pos, topDir);
			let rightDir = cc.v2(1, 1).normalizeSelf();
			this.fireBall(pos, rightDir);
		} else if (propType == PROP_TYPE.TIMES3) {
			let len = this.currBalls.length;
			let maxBall = cc.sys.os == cc.sys.OS_IOS ? Global.MAX_BALLS * 0.25 : Global.MAX_BALLS;
			for (let i = 0; i < len; ++i) {
				if (this.currBalls.length > maxBall) {
					// cc.error('too many balls.');
					break;
				}
				let ball = this.currBalls[i];
				let leftDir = cc.v2(Math.random() * 2 - 1, Math.random() * 2 - 1).normalizeSelf();
				this.fireBall(ball.node.position, leftDir);
				this.scheduleOnce(()=>{
					let topDir = cc.v2(Math.random() * 2 - 1, Math.random() * 2 - 1).normalizeSelf();
					this.fireBall(ball.node.position, topDir);
				}, 0);
				this.scheduleOnce(()=>{
					let rightDir = cc.v2(Math.random() * 2 - 1, Math.random() * 2 - 1).normalizeSelf();
					this.fireBall(ball.node.position, rightDir);
				}, 0.016);
			}
		} else if (propType == PROP_TYPE.WALL) {
			this.wallNode.stopAllActions();
			this.wallNode.active = true;
			this.wallNode.opacity = 255;
			this.wallNode.runAction(
				cc.sequence(
					cc.delayTime(Global.WALL_TIME),
					cc.blink(1, 3),
					cc.callFunc(
						() => {
							this.wallNode.active = false;
						}
					)
				)
			)
		}
	}

	recycleProp(prop: Prop) {
		if (prop.propType == PROP_TYPE.SHOOT3) {
			PoolManager.Ins.put(PoolType.PROP_SHOOT, prop.node);
		} else if (prop.propType == PROP_TYPE.TIMES3) {
			PoolManager.Ins.put(PoolType.PROP_TIMES, prop.node);
		} else if (prop.propType == PROP_TYPE.WALL) {
			PoolManager.Ins.put(PoolType.PROP_WALL, prop.node);
		}
	}

	fireBall(pos: cc.Vec2, direction: cc.Vec2) {
		let ball = this.createBall();
		ball.node.position = pos;
		ball.fire(direction);

		this.currBalls.push(ball);
	}

	recycleBall(ball: Ball) {
		PoolManager.Ins.put(PoolType.BALL, ball.node);
		let idx = this.currBalls.indexOf(ball);
		if (idx != -1) {
			this.currBalls.splice(idx, 1);
			cc.log('recycle a ball.');
			if (this.currBalls.length == 0) {
				cc.log('Game over.');
				Game.instance.gameover();
			}
		}
	}

	clearProps() {
		let count = this.propsRootNode.childrenCount;
		for (let i = count - 1; i >= 0; --i) {
			let _node = this.propsRootNode.children[i];
			this.recycleProp(_node.getComponent(Prop));
		}
	}

	clearBalls() {
		let count = this.ballsRootNode.childrenCount;
		for (let i = count - 1; i >= 0; --i) {
			let _node = this.ballsRootNode.children[i];
			PoolManager.Ins.put(PoolType.BALL, _node);
		}

		this.currBalls = [];
	}

	clearBricks() {
		let count = this.bricksRootNode.childrenCount;
		for (let i = count - 1; i >= 0; --i) {
			let _node = this.bricksRootNode.children[i];
			PoolManager.Ins.put(PoolType.BRICK, _node);
		}

		this.obstacleBricks = [];
		this.breakableBricks = [];
	}

	recycleBrick(brick: Brick, isClear = false) {
		let worldPos = brick.node.convertToWorldSpaceAR(cc.Vec2.ZERO);
		PoolManager.Ins.put(PoolType.BRICK, brick.node);
		let idx = this.breakableBricks.indexOf(brick);
		if (idx != -1) {
			this.breakableBricks.splice(idx, 1);
			cc.log('recycle a brick.')

			if (isClear) {
				return;
			}

			if (this.breakableBricks.length == 0) {//win
				cc.log('You win.');
				Game.instance.showResultLayer(true);
				return;
			}

			this.recycleBrickCounter++;
			if (this.recycleBrickCounter == Global.getPropDropCount(this.createPropTimes, Userdata.SelectLevel)) {
				cc.log('recycleBrickCounter: ' + this.recycleBrickCounter + ' , prop drops: ' + this.createPropTimes);
				this.recycleBrickCounter = 0;
				this.createPropTimes++;
				this.generateProp(worldPos);//生成一个道具
			}
		}
	}

	generateProp(worldPos: cc.Vec2) {
		let propType = Global.getNextPropType(Userdata.SelectLevel);

		let prop = this.createProp(propType);
		prop.node.position = this.propsRootNode.convertToNodeSpaceAR(worldPos);
	}

	resetButtonTip() {
		this.buttonShootNode.angle = 0;
		this.buttonShootNode.stopAllActions();
		this.buttonTimesNode.angle = 0;
		this.buttonTimesNode.stopAllActions();
		this.buttonWallNode.angle = 0;
		this.buttonWallNode.stopAllActions();
	}

	showButtonTipActions() {
		this.runTipUseTimeAction(this.buttonShootNode);
		this.runTipUseTimeAction(this.buttonTimesNode);
		this.runTipUseTimeAction(this.buttonWallNode);
	}

	private runTipUseTimeAction(node: cc.Node) {
		if (node.active) {
			node.stopAllActions();
			node.runAction(
				cc.repeatForever(
					cc.sequence(
						// cc.scaleTo(0.5, 0.9),
						// cc.scaleTo(0.5, 1)
						cc.rotateTo(0.1, -5),
						cc.rotateTo(0.1, 5),
						cc.rotateTo(0.1, 0)
					)
				)
			);
		}
	}

}
