<script>
import { defineComponent } from 'vue'
import Sidebar from '@/components/Sidebar.vue'
import Cookies from 'js-cookie'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { config } from '@/main.js'

export default defineComponent({
	name: 'UploadView',
	setup() {
		const router = useRouter()
		// no this here
		if (!Cookies.get('token') || !Cookies.get('token').startsWith('HajeebToken'))
			return router.push('/profile/myself')
		return { router }
	},
	components: { Sidebar },
	methods: {
		async handleSubmit(e) {
			e.preventDefault()
			if (!this.signedIn()) return this.router.push('/login');
			document.getElementById('submit').disabled = true

			const formData = new FormData(e.target);
			const response = await axios.post(`${config.serverURL}/video/upload`, formData, {
				withCredentials: true,
			})

			if(response.data.error) {
				if(response.data.error === 400) {
					response.data.message = "Video file too big!";
				}
				alert(`Upload error: ${response.data.message}`);
				console.error(response.data)
				return this.router.push(`/upload`);
			}

			if(response.data.id) {
				alert(`Video uploaded successfully!`);
				return this.router.push(`/profile/myself`);
			}
		},
		signedIn() {
			return Cookies.get('token') && Cookies.get('token').startsWith('HajeebToken')
		},
	},
})
</script>

<template>
	<div class="main">
		<Sidebar />
		<div class="upload-container">
			<form class="upload" id="form" @submit="handleSubmit" enctype="multipart/form-data">
				<img src="/assets/hajeebtok.png" width="300px" alt="HajeebTok logo" />
				<input
					type="file"
					name="video"
					accept="video/mp4, video/ogg, video/x-matroska, video/webm"
				/>
				<input type="text" placeholder="title" name="title" />
				<input type="text" placeholder="description" name="description" />
				<input type="submit" value="Upload Video" id="submit" />
			</form>
		</div>
	</div>
</template>

<style scoped>
.upload-container {
	width: 100vw;
	height: 100vh;
	margin: 0;
	position: absolute;

	display: flex;
	justify-content: center;
	align-items: center;
	top: 0;
}

.upload {
	background-color: var(--secondary-background-color);
	color: white;

	padding: 10px;
	border-radius: 5px;

	display: flex;
	flex-direction: column;
	align-items: center;
	justify-self: center;
	gap: 10px;
}

input {
	font-family: 'Knewave', system-ui;
	font-size: 30px;

	border: 2px solid var(--accent-color);
	border-radius: 5px;
}

input:focus {
	outline: none;
}
</style>
