
initDom();
function initDom() {
	document.getElementById("play_pong_button").addEventListener("click", init);
}

import * as c from "./constants.js"
import * as en from "../shared_js/enums.js"
import { GameArea } from "./class/GameArea.js";
import { GameComponentsClient } from "./class/GameComponentsClient.js";
import { handleInput } from "./handleInput.js";
// import { sendLoop } from "./handleInput.js";
import { gameLoop } from "./gameLoop.js"
import { drawLoop } from "./draw.js";
import { countdown } from "./utils.js";
import { initWebSocket } from "./ws.js";
import { initAudio } from "./audio.js";


/* Keys
	Racket: W/S OR Up/Down
	Grid On-Off: G
*/

/* TODO: A way to delay the init of variables, but still use "const" not "let" ? */
export let pong: GameArea;
export let gc: GameComponentsClient;
export let matchOptions: en.MatchOptions = en.MatchOptions.noOption;

function init()
{
	console.log("multi_balls:"+(<HTMLInputElement>document.getElementById("multi_balls")).checked);
	console.log("moving_walls:"+(<HTMLInputElement>document.getElementById("moving_walls")).checked);
	console.log("sound_on:"+(<HTMLInputElement>document.getElementById("sound_on")).checked);

	let soundMutedFlag = false;
	if ( (<HTMLInputElement>document.getElementById("sound_off")).checked ) {
		soundMutedFlag = true;
	}
	initAudio(soundMutedFlag);

	if ( (<HTMLInputElement>document.getElementById("multi_balls")).checked ) {
		matchOptions |= en.MatchOptions.multiBalls;
	}
	if ( (<HTMLInputElement>document.getElementById("moving_walls")).checked ) {
		matchOptions |= en.MatchOptions.movingWalls;
	}

	document.getElementById("div_game_options").hidden = true;

	pong = new GameArea();
	gc = new GameComponentsClient(matchOptions, pong.ctx);
	initWebSocket(matchOptions);
}

function matchmaking()
{
	console.log("Searching an opponent...");
	gc.text1.clear();
	gc.text1.pos.assign(c.w/5, c.h_mid);
	gc.text1.text = "Searching...";
	gc.text1.update();
}

function matchmakingComplete()
{
	console.log("Match Found !");
	gc.text1.clear();
	gc.text1.pos.assign(c.w/8, c.h_mid);
	gc.text1.text = "Match Found !";
	gc.text1.update();
}

function startGame() {
	gc.text1.pos.assign(c.w_mid, c.h_mid+c.h/4);
	countdown(c.matchStartDelay/1000, (count: number) => {
		gc.text1.clear();
		gc.text1.text = `${count}`;
		gc.text1.update();
	}, resumeGame);
}

function resumeGame()
{
	gc.text1.text = "";
	window.addEventListener('keydown', function (e) {
		pong.addKey(e.key);
	});
	window.addEventListener('keyup', function (e) {
		pong.deleteKey(e.key);
	});
	pong.handleInputInterval = window.setInterval(handleInput, c.handleInputIntervalMS);
	// pong.handleInputInterval = window.setInterval(sendLoop, c.sendLoopIntervalMS);
	pong.gameLoopInterval = window.setInterval(gameLoop, c.gameLoopIntervalMS);
	pong.drawLoopInterval = window.setInterval(drawLoop, c.drawLoopIntervalMS);
}


export {matchmaking, matchmakingComplete, startGame}
