import AbstractAuthenticatedView from "./abstracts/AbstractAuthenticatedView.js";

export class PongOfflineView extends AbstractAuthenticatedView {
	constructor(params) {
		super(params, 'Game');
		this.game = null;
		this.player1 = "Player 1";
		this.player2 = "Player 2";
	}

	async getHtml() {
		return `
			<link rel="stylesheet" href="/static/css/gameOffline.css">
			<h1>Game</h1>
			<button id='startGameButton'>Start Game</button>
			<button id='stopGameButton'>Stop Game</button>
			<button id='startTournament'>Start Tournament</button>
		`;
	}

	async postInit() {
		this.app = document.getElementById("app");
		document.getElementById('startGameButton').onclick = this.startGame.bind(this);
		document.getElementById('stopGameButton').onclick = this.stopGame.bind(this);
		document.getElementById('stopGameButton').hidden = 1;
		document.getElementById('startTournament').onclick = this.startTournament.bind(this);
	}

	async leavePage() {
		this.game?.cleanup();
	}

	startTournament() {
		let startTournament = document.getElementById("startTournament");
		let player1 = document.createElement("input");
		player1.id="player1"; player1.type="text"; player1.name="message"; player1.placeholder="Player 1"; player1.maxLength=20; player1.value = "";
		startTournament.before(player1);

		let player2 = document.createElement("input");
		player2.id="player2"; player2.type="text"; player2.name="message"; player2.placeholder="Player 2"; player2.maxLength=20; player2.value = "";
		player1.after(player2);

		/*let player3 = document.createElement("input");
		player3.id="player3"; player3.type="text"; player3.name="message"; player3.placeholder="Player 3"; player3.maxLength=20;
		player2.after(player3);

		let player4 = document.createElement("input");
		player4.id="player4"; player4.type="text"; player4.name="message"; player4.placeholder="Player 4"; player4.maxLength=40;
		player3.after(player4);*/

		startTournament.onclick = () => {
			if (player1.value.length > 0)
				this.player1 = player1.value;
			if (player2.value.length > 0)
				this.player2 = player2.value;
			/*if (player3.value.length > 0)
				this.player3 = player3.value;
			if (player4.value.length > 0)
				this.player4 = player4.value;*/

			player1.remove();
			player2.remove();

			this.startGame(this.player1, this.player2);
			startTournament.onclick = this.startTournament.bind(this);
		}
	}

	createButton()
	{
		this.up1 = document.createElement("button");
		this.up1.textContent = "↑";
		this.up1.id = "up1";

		this.down1 = document.createElement("button");
		this.down1.textContent = "↓";
		this.down1.id = "down1";

		this.up2 = document.createElement("button");
		this.up2.textContent = "↑";
		this.up2.id = "up2";

		this.down2 = document.createElement("button");
		this.down2.textContent = "↓";
		this.down2.id = "down2";

		this.up1.setAttribute("user_id", 1);
		this.up1.setAttribute("direction", "up");
		this.up2.setAttribute("user_id", 2);
		this.up2.setAttribute("direction", "up");

		this.down1.setAttribute("user_id", 1);
		this.down1.setAttribute("direction", "down");
		this.down2.setAttribute("user_id", 2);
		this.down2.setAttribute("direction", "down");

		document.addEventListener('touchstart', this.keyDownHandler);
		document.addEventListener('touchend', this.keyUpHandler);
		[this.up1, this.up2, this.down1, this.down2].forEach(button => {
			button.onmousedown = this.game.keyDownHandler.bind(this.game);
			button.onmouseup = this.game.keyUpHandler.bind(this.game);
			button.ontouchstart = this.game.keyDownHandler.bind(this.game);
			button.ontouchend = this.game.keyUpHandler.bind(this.game);
		});

		document.getElementById("gameCanvas").after(this.up2, this.down2);
		document.getElementById("gameCanvas").after(this.up1, this.down1);
	}

	startGame(player1, player2) {
		if (player1 == null || player2 == null) {
			player1 = this.player1;
			player2 = this.player2;
		}
		if (this.game == null) {
			document.getElementById('startGameButton').innerHTML = 'Reset Game';
			this.game = new Game(player1, player2);
			this.createButton();
		}
		else {
			this.app.removeChild(this.game.canvas);
			this.app.removeChild(this.game.scoresDisplay);
			this.game.cleanup();
			this.game = new Game(player1, player2);
			this.createButton();
		}
		document.getElementById('startTournament').hidden = 1;
		document.getElementById('stopGameButton').hidden = 0;
	}

	stopGame() {
		if (!this.game)
			return;
		this.app.removeChild(this.game.canvas);
		this.app.removeChild(this.game.scoresDisplay);
		this.game.cleanup();
		this.game = null;
		document.getElementById('startGameButton').innerHTML = 'Start Game';
		document.getElementById('startTournament').hidden = 0;
		document.getElementById('stopGameButton').hidden = 1;
		this.app.style.maxWidth = null;
	}
}

class Game {
	constructor(player1, player2) {
		//Global variables
		this.def = {
			CANVASHEIGHT: 270,
			CANVASWIDTH: 480,
			PADDLEHEIGHT: 70,
			PADDLEWIDTH: 10,
			PADDLEMARGIN: 5,
			PADDLESPEED: 3,
			BALLRADIUS: 5,
			BALLSPEED: 2,
			BALLSPEEDINCR: 0.15,
			MAXBOUNCEANGLE: 10 * (Math.PI / 12),
			MAXSCORE: 0
		};

		this.app = document.getElementById("app");
		this.app.style.maxWidth = Number(this.def.CANVASWIDTH) + "px";

		this.player1 = player1;
		this.player2 = player2;

		this.canvas = document.createElement('canvas');
		this.canvas.id = 'gameCanvas';
		this.canvas.width = this.def.CANVASWIDTH;
		this.canvas.height = this.def.CANVASHEIGHT;
		this.canvas.style.border = '1px solid #d3d3d3';
		this.canvas.style.backgroundColor = '#f1f1f1';
		this.context = this.canvas.getContext('2d');
		this.app.appendChild(this.canvas);
		this.scoresDisplay = document.createElement('p');
		this.scoresDisplay.innerHTML = `${this.player1}: 0 - ${this.player2}: 0`;
		this.app.appendChild(this.scoresDisplay);

		this.players = [
			{
				paddle: new Paddle(this.context,
							this.def.PADDLEMARGIN,
							this.def),
				score: 0
			},
			{
				paddle: new Paddle(this.context,
							this.def.CANVASWIDTH - this.def.PADDLEMARGIN - this.def.PADDLEWIDTH,
							this.def),
				score: 0
			}
		];
		this.ballStartSide = 0;
		this.ballRespawned = false;
		this.ball = new Ball(this.context, this.def, this.ballStartSide);

		this.interval = setInterval(this.updateGame.bind(this), 10);

		this.keys = [];
		this.keyUpHandler = this.keyUpHandler.bind(this);
		this.keyDownHandler = this.keyDownHandler.bind(this);
		document.addEventListener('keydown', this.keyDownHandler);
		document.addEventListener('keyup', this.keyUpHandler);

	}

	cleanup() {
		clearInterval(this.interval);
		document.removeEventListener('keydown', this.keyDownHandler);
		document.removeEventListener('keyup', this.keyUpHandler);
		this.canvas.style.display = 'none';
		["up1", "up2", "down1", "down2", "player1", "player2"].forEach(button => {
			if (document.getElementById(button) != null)
				document.getElementById(button).remove();
		});
	}

	clear() {
		this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
	}

	updateGame() {
		//Paddle movement
		/*let log = document.getElementById("log");
		console.log(log);
		log.setAttribute("log", this.keys)
		log.innerText = "keys: " + log.getAttribute("log");*/
		if ((this.keys.includes('s') || this.keys.includes('down1')) &&
			this.players[0].paddle.y + this.def.PADDLEHEIGHT < this.def.CANVASHEIGHT - this.def.PADDLEMARGIN)
				this.players[0].paddle.y += this.def.PADDLESPEED;
		if ((this.keys.includes('w') || this.keys.includes('up1')) &&
			this.players[0].paddle.y > 0 + this.def.PADDLEMARGIN)
				this.players[0].paddle.y -= this.def.PADDLESPEED;

		if ((this.keys.includes('ArrowDown') || this.keys.includes('down2')) &&
			this.players[1].paddle.y + this.def.PADDLEHEIGHT < this.def.CANVASHEIGHT - this.def.PADDLEMARGIN)
				this.players[1].paddle.y += this.def.PADDLESPEED;
		if ((this.keys.includes('ArrowUp') || this.keys.includes('up2')) &&
			this.players[1].paddle.y > 0 + this.def.PADDLEMARGIN)
				this.players[1].paddle.y -= this.def.PADDLESPEED;

		//GOOAAAAL
		if (this.ball.x <= 0)
			this.updateScore.bind(this)(this.players[0].score, ++this.players[1].score);
		else if (this.ball.x >= this.def.CANVASWIDTH)
			this.updateScore.bind(this)(++this.players[0].score, this.players[1].score);

		//Ball collisions
		if (this.detectCollision(this.players[0].paddle, this.ball))
			this.calculateBallVelocity(this.players[0].paddle.getCenter().y, this.ball);
		else if (this.detectCollision(this.players[1].paddle, this.ball))
			this.calculateBallVelocity(this.players[1].paddle.getCenter().y, this.ball, -1);

		if (this.ball.y - this.ball.radius <= 0)
			this.ball.vy *= -1;
		else if (this.ball.y + this.ball.radius >= this.canvas.height)
			this.ball.vy *= -1;

		if (!this.ballRespawned) {
			this.ball.x += this.ball.vx;
			this.ball.y += this.ball.vy;
		}

		this.clear();
		this.players[0].paddle.update();
		this.players[1].paddle.update();
		this.ball.update();
	}

	updateScore(p1Score, p2Score) {
		if (p1Score > this.def.MAXSCORE) {
			this.scoresDisplay.innerHTML = this.player1 + ' wins!! GGS';
			this.cleanup();
		}
		else if (p2Score > this.def.MAXSCORE) {
			this.scoresDisplay.innerHTML = this.player2 + ' wins!! GGS';
			this.cleanup();
		} else {
			this.scoresDisplay.innerHTML = `${this.player1}: ${p1Score} - ${this.player2}: ${p2Score}`;
			this.ballStartSide = 1 - this.ballStartSide;
			this.ball = new Ball(this.context, this.def, this.ballStartSide);
			this.ballRespawned = true;
			new Promise(r => setTimeout(r, 300))
				.then(_ => this.ballRespawned = false);
		}
	}

	detectCollision(paddle, ball) {
		let paddleCenter = paddle.getCenter();
		let dx = Math.abs(ball.x - paddleCenter.x);
		let dy = Math.abs(ball.y - paddleCenter.y);
		if (dx <= ball.radius + paddle.width / 2 &&
			dy <= ball.radius + paddle.height / 2)
				return true;
		return false;
	}

	calculateBallVelocity(paddleCenterY, ball, side = 1) {
		let relativeIntersectY = paddleCenterY - ball.y;
		let normRelIntersectY = relativeIntersectY / this.def.PADDLEHEIGHT / 2;
		let bounceAngle = normRelIntersectY * this.def.MAXBOUNCEANGLE;

		ball.speed += this.def.BALLSPEEDINCR;
		ball.vx = ball.speed * side * Math.cos(bounceAngle);
		ball.vy = ball.speed * -Math.sin(bounceAngle);
	}

	keyUpHandler(ev) {
		let attributes = ev.originalTarget.attributes;

		let key = ev.key === undefined ? `${attributes.direction.value}${attributes.user_id.value}` : ev.key;

		const idx = this.keys.indexOf(key);
		if (idx != -1)
			this.keys.splice(idx, 1);
	}

	keyDownHandler(ev) {
		let attributes = ev.originalTarget.attributes;

		let key = ev.key === undefined ? `${attributes.direction.value}${attributes.user_id.value}` : ev.key;

		if (!this.keys.includes(key))
			this.keys.push(key);
	}
}

class Paddle {
	constructor(context, paddleSide, def) {
		this.width = def.PADDLEWIDTH;
		this.height = def.PADDLEHEIGHT;
		this.x = paddleSide;
		this.y = def.CANVASHEIGHT / 2 - this.height / 2;
		this.ctx = context;
		this.update();
	}

	update() {
		this.ctx.fillStyle = 'black';
		this.ctx.fillRect(this.x, this.y, this.width, this.height);
	}

	getCenter() {
		return {
			x: this.x + this.width / 2,
			y: this.y + this.height / 2
		};
	}
}

class Ball {
	constructor(context, def, startSide) {
		this.radius = def.BALLRADIUS;
		this.speed = def.BALLSPEED;
		this.x = def.CANVASWIDTH / 2;
		this.y = def.CANVASHEIGHT / 2;
		this.vy = 0;
		if (startSide === 0)
			this.vx = -this.speed;
		else
			this.vx = this.speed;
		this.ctx = context;
		this.update();
	}

	update() {
		this.ctx.fillStyle = 'black';
		this.ctx.beginPath();
		this.ctx.arc(this.x, this.y, this.radius, 0, 2 * Math.PI);
		this.ctx.fill();
	}
}
