<template>
	<div>
		<form @submit.prevent>
			<label for="user">Username</label>
			<input id="user" v-model="user" type="text" />
			<button :disabled="!user" @click="login">Login</button>
		</form>

		{{ user }}, {{ id }}
	</div>
</template>

<script>
import { nanoid } from 'nanoid'
import { useLocalStorage } from '@vueuse/core'
import connectWebsocket from '~/composables/connectWebsocket'

export default {
	name: 'AuthPage',
	setup() {
		const { data, send, open } = connectWebsocket()

		return {
			data,
			send,
			open,
		}
	},
	data() {
		return {
			user: '',
			id: '',
		}
	},
	mounted() {
		this.open()
		this.id = useLocalStorage('ooc_user_id', nanoid())
	},
	methods: {
		login() {
			this.$store.commit('auth/setUser', this.user)
			this.$store.commit('auth/setId', this.id)
			this.send(
				JSON.stringify({
					type: 'new_user',
					user: this.user,
					id: this.id,
				})
			)
			this.$router.push('/')
		},
	},
}
</script>

<style>
button:disabled {
	background-color: red;
}
</style>