<template>
	<div class="container">
		<b-table
			striped
			hoverable
			:data="rooms"
			:columns="columns"
			@click="rowClicked"
		></b-table>
	</div>
</template>

<style lang="scss" scoped>
.b-table {
	cursor: pointer;
}
</style>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { State, Action } from "vuex-class";
import { ServerState } from "@/store/server";
import { Room } from "@/store/room";

const columns = [
	{
		field: "game_id",
		label: "Game"
	},
	{
		field: "name",
		label: "Name"
	},
	{
		field: "creator",
		label: "Creator"
	},
	{
		field: "can_spectate",
		label: "Spectators allowed"
	},
	{
		field: "players",
		label: "Players",
		numeric: true
	},
	{
		field: "spectators",
		label: "Spectators",
		numeric: true
	}
];

interface RoomRow {
	id: string;
	game_id: string;
	name: string;
	creator: string;
	players: number;
	spectators: number;
	can_spectate: string;
}

@Component({})
export default class RoomList extends Vue {
	@State("server") private server!: ServerState;
	@Action("joinRoom", { namespace: "server" }) private join: any;

	private data() {
		return {
			columns
		};
	}

	private get rooms(): RoomRow[] {
		if (this.server.rooms == null) {
			return [];
		}
		let rooms: RoomRow[] = [];
		for (const room of this.server.rooms) {
			rooms.push({
				id: room.id,
				game_id: room.game_id,
				name: room.name,
				creator: room.creator,
				players: room.current_players,
				spectators: room.current_spectators,
				can_spectate: room.can_spectate ? "Yes" : "No"
			});
		}
		return rooms;
	}

	private rowClicked(row: RoomRow) {
		this.join({
			roomid: row.id,
			as_spectator: row.can_spectate == "Yes"
		});
	}
}
</script>
