<template>
	<div id="game_lobby">
		<h1>
			Secret Hitler Online
		</h1>
		<h2>
			Username: {{ username }}
			<br>
			Game Code:
			<code
				v-clipboard="() => {return this.game_code}"
				v-clipboard:success="copy_success"
				v-clipboard:error="copy_error"
			>
				{{ game_code }}
			</code>
		</h2>
		<div id="player-list">
			<h3>Players:</h3>
			<div
				v-for="player in players"
				:key="player"
				class="player"
			>
				<div class="name">
					{{ player }}
				</div>
				<button
					v-if="is_host"
					class="kick"
					:disabled="player === username"
					@click.stop="kick_player(player)"
				>
					Kick
				</button>
			</div>
		</div>
		<div class="controls">
			<button>Start Game</button>
			<br>
			<button>{{ is_host ? `Kill` : `Leave` }} Game</button>
		</div>
	</div>
</template>

<script>
export default {
	name: 'GameLobby',
	components: {},
	data() {return {
		game_code: ``,
		is_host: false,
		username: ``,
		players: [],
	}},
	mounted() {
		this.game_code = sessionStorage.getItem(`game-code`);
		this.is_host = JSON.parse(sessionStorage.getItem(`is-host`));
		this.username = sessionStorage.getItem(`user-name`);
		this.$nextTick(() => this.getPlayerList());
	},
	methods: {
		getPlayerList() {
			this.$socket.emit(`GetPlayerList`, {
				game_code: this.game_code,
			});
		},
		copy_success() {
			this.$emit(`alert`, {
				message: `Game code copied to your clipboard.`,
				classes: [`info`]
			});
			setTimeout(() => this.$emit(`alert`, { message: ``, classes: [] }), 2000);
		},
		copy_error() {
			this.$emit(`alert`, {
				message: `Something went wrong when copying the game code to your clipboard`,
				classes: [`warning`]
			});
			setTimeout(() => this.$emit(`alert`, { message: ``, classes: [] }), 2000);
		},
		handle_exit_button() {
			if (this.is_host) {
				let cont = confirm(`Are you sure you want to exit`);
				if (cont) {
					alert(`exiting game`)
				};
			} else {
				this.$socket.emit(`LeaveGame`, {
					username: this.username
				});
			};
		},
	},
	sockets: {
		PlayerListResponse(data) {
			if (data.success) {
				this.players = data.players;
			} else {
				this.$emit(`alert`, {
					message: data.message,
					classes: [`warning`],
				});
			};
		},
		NewPlayer(data) {
			this.players.push(data.player);
		},
	},
}
</script>

<style scoped>
@import "../css/colours.css";

#game_lobby {
	text-align: center;
	width: 90vw;
}

.player {
	background-color: var(--card-background-colour);
	justify-content: space-between;
	color: var(--card-text-colour);
	margin: 5px auto;
	display: flex;
	width: 30vw;
}

.name {
	align-items: center;
	display: flex;
	flex-grow: 2;
	margin: 5px;
}

.kick {
	margin: 5px;
}
</style>