<template>
	<n-config-provider :theme="darkTheme">
		<div id="all">
			<div id="group_select">
				<n-select v-model:value="selected_group" :options="groups" size="large" />
				<n-button secondary type="primary" @click="showAddGroupModal = true" size="large">
					<n-icon><CreateNewFolderRound /></n-icon>
				</n-button>
			</div>

			<div id="camera">
				<div id="prompt_select" v-show="!selected_group">
					<n-icon size="4em"><HandPointUp/></n-icon><br/>
					<h1 class="text-3xl font-bold">Please select a photo group</h1>
					<p class="text-xl font-bold">(or create a new one)</p>
				</div>
				<h1 class="text-xl font-bold" style="margin-top: 40%; text-align: center" v-if="selected_group && !photo_src">Please take a new photo</h1>
				<n-spin :show="isUploading">
					<n-image :src="photo_src" v-if="selected_group && photo_src" />
				</n-spin>
			</div>

			<div id="take_photo">
				<n-space justify-content="center">
					<label for="camera_file_input">
						<span :class="{disabled: !selected_group, camera_btn: true}">Take new photo</span>
						<input
							type="file"
							id="camera_file_input"
							accept="image/*"
							capture="environment"
							@change="previewImage"
							:disabled="!selected_group"
						/>
					</label>
					<n-button v-if="selected_group && photo_src"
						type="info" size="large" round
						@click="uploadPhoto"
					>Upload</n-button>
				</n-space>
			</div>
		</div>

		<n-modal
			v-model:show="showAddGroupModal"
			:mask-closable="true"
			transform-origin="center"
			preset="card"
			title="Add new Group"
			:bordered="false"
			size="huge">

			<n-input placeholder="Enter group name" size="large" v-model:value="new_group_name" />

			<template #footer>
				<n-space justify-content="end">
					<n-button size="large" @click="showAddGroupModal = false">Cancel</n-button>
					<n-button type="primary" size="large" @click="addNewGroup">Add Group</n-button>
				</n-space>
			</template>
		</n-modal>
	</n-config-provider>
</template>

<script>
import { useMeta } from 'vue-meta'
import { useMessage } from 'naive-ui'
import {darkTheme} from 'naive-ui'

import CreateNewFolderRound from '@vicons/material/CreateNewFolderRound'
import HandPointUp from '@vicons/fa/HandPointUp'

import { getPhotoGroups, addNewPhotoGroup, addNewPhoto, cropPhoto } from '@/api'

export default {
	components: {
		CreateNewFolderRound,
		HandPointUp,
	},
	setup() {
		useMeta({
			title: 'Capture new Photo',
		})
		const message = useMessage()
		return { message }
	},
	data() {
		return {
			darkTheme,

			groups: [],
			selected_group: null,
			showAddGroupModal: false,

			new_group_name: '',

			isPhotoTaken: false,
			photo_src: '',
			photo_file: null,

			isUploading: false,
		}
	},
	beforeMount() {
		this.fetchPhotoGroups()
	},
	mounted() {
		window.scrollTo(0, 1)
	},
	computed: {
		selected_group_label() {
			if (this.selected_group !== null && this.groups.length > 0) {
				return this.groups.filter(group => group.value === this.selected_group)[0].label
			}
			return ''
		},
	},
	methods: {
		fetchPhotoGroups() {
			this.groups = []
			getPhotoGroups().then((response) => {
				let data = response.data
				data = this.sortPhotoGroupsByDate(data)
				for(const data_idx in data) {
					this.groups.push({
						label: data[data_idx].name,
						value: data[data_idx].id,
					})
				}
			}).catch((error)=>{
				this.message.error('There was an error while fetching photo groups: '+error)
			})
		},
		sortPhotoGroupsByDate(groups) {
			if (groups !== null && groups.length > 0) {
				groups = [...groups].sort((a,b) => {
					if (a.date === null) return 1
					if (b.date === null) return -1
					return a.date > b.date ? -1 : 1
				})
				// move group with id 1 ("unsorted"-group) to front
				let index = groups.indexOf(groups.filter(g=>g.id==1)[0])
				groups.unshift(groups.splice(index, 1)[0])
				return groups
			}
			return []
		},
		addNewGroup() {
			if (this.new_group_name.length == 0) {
				this.message.error('Please enter a new group name')
				return
			}

			let today = new Date()
			let dd = String(today.getDate()).padStart(2, '0')
			let mm = String(today.getMonth() + 1).padStart(2, '0')
			let yyyy = today.getFullYear()
			today = yyyy + '-' + mm + '-' + dd

			addNewPhotoGroup(this.new_group_name, today).then((response) => {
				this.message.success('Added group '+this.new_group_name)
				this.fetchPhotoGroups()
				this.showAddGroupModal = false
				this.selected_group = response.data.id
			}).catch((error)=>{
				this.message.error('There was an error while adding the group: '+error)
			}).finally(() => {
				this.new_group_name = ''
			})
		},
		previewImage(event) {
			let files = event.target.files
			this.photo_file = files[0]
			this.photo_src = window.URL.createObjectURL(this.photo_file)
		},
		uploadPhoto() {
			this.isUploading = true
			
			addNewPhoto(this.photo_file, null, this.selected_group).then((response) => {
				this.message.success('Done!')

				this.isUploading = false
				this.photo_src = ''
				this.photo_file = null

				setTimeout(() => {
					cropPhoto(response.data.id, 'auto').then(()=>{
						console.log('photo has been cropped')
					}).catch((error)=>{
						console.error(error)
					})
				}, 100)
			}).catch((error) => {
				this.message.error('There was an error uploading the photo: ' + error)
			})
		},
	},
}
</script>

<style scoped>
html, body {
	margin: 0;
	padding: 0;
	overflow: hidden;
	height: 100vh;
}

#all {
	background-color: #111;
	width: 100vw;
	height: 100vh;
	display: flex;
	flex-direction: column;
	flex-wrap: nowrap;
	overflow: hidden;
	color: white;
	margin: 0;
	padding: 0;
}

#camera_preview {
	height: 75vh;
	width: 100%;
}

#group_select {
	display: flex;
	height: 7.5vh;
}

#prompt_select {
	display: flex;
	flex-direction: column;
	text-align: center;
	margin-top: 25vh;
}

#prompt_select .n-icon {
	margin: auto;
}

#camera_file_input {
	display: none;
}

#take_photo {
	height: 15vh;
	background-color: #222;
	display: flex;
	justify-content: center;
	bottom: 0;
	position: fixed;
	width: 100%;
}

#take_photo .camera_btn {
	margin-top: 5vh;
	display: inline-block;
	background-color: #7ec090;
	color: white;
	padding: 0.5em 1em;
	border-radius: 2em;
	font-size: 16px;
	cursor: pointer;
}

#take_photo .n-button {
	margin-top: 5vh;
}

.camera_btn:hover {
	filter: brightness(0.9);
}

.disabled {
	filter: brightness(0.75) !important;
	cursor: not-allowed !important;
}
</style>