<template>
	<div>
		<h1>Manage Photos</h1>
		<n-collapse
			v-if="photoGroups && photoGroups.length > 0"
			@item-header-click="loadPhotosInGroup"
		>
			<n-collapse-item
				v-for="group in photoGroups" :key="group.id"
				:title="group.name"
				:name="group.id">
				<template #header-extra>{{ group.date }}</template>

				<div style="text-align: center">
					<p v-if="is_group_loading.get(group.id)">loading...</p>
					<p v-else-if="!photos[group.id]">no photos in group found</p>
				</div>

				<n-space>
					<PhotoItem
						v-for="(photo, idx) in photos[group.id]" :key="idx"
						:src="getPhotoSrcById(photo.id)"
						:can_change_group="true"
						:can_crop="true"
						:can_change_ocr="true"
						:can_delete="true"
						@update:group="change_group_modal(photo.id)"
						@update:crop="change_crop_modal(photo.id)"
						@update:ocr="change_ocr_modal(photo.id)"
						@update:delete="change_delete_modal(photo.id)"
					/>
				</n-space>
			</n-collapse-item>
		</n-collapse>
		<p v-else>No Photo Groups</p>

		<n-modal 
			v-model:show="showCropModal"
			:mask-closable="false" 
		>
			<n-card
				style="width: 95vw; min-height: 90vh;"
				title="Adjust Photo Cropping"
				:bordered="true"
			>

				<PhotoCropper
					style="max-width:75vw;margin:auto;"
					:src="current_photo_src"
					:inters="current_photo_intersections"
					ref="cropper"
				/>
				
				<template #action>
					<n-space justify="end">
						<n-button @click="showCropModal = false">Cancel</n-button>
						<n-button type="primary" @click="changeCrop">Save</n-button>
					</n-space>
				</template>
			</n-card>
		</n-modal>

		<n-modal
			v-model:show="showChangeGroupModal"
			:mask-closable="true" >
			<n-card
				style="width: 400px;"
				title="Move to Photo Group"
				:bordered="false"
				role="dialog"
				aria-modal="true"
				>
				<n-select v-model:value="new_group" :options="groups_select_options" />
				<template #footer>
					<n-space justify="end">
						<n-button @click="showChangeGroupModal=false">Cancel</n-button>
						<n-button type="success" @click="changePhotoGroup">Move to Group</n-button>
					</n-space>
				</template>
			</n-card>
		</n-modal>

		<n-modal
			v-model:show="showDeleteModal"
			:mask-closable="true" >
			<n-card
				style="width: 400px;"
				title="Delete Photo"
				:bordered="false"
				role="dialog"
				aria-modal="true"
				>
				Do you want to permanently delete the photo?
				<template #footer>
					<n-space justify="end">
						<n-button @click="showDeleteModal=false">Cancel</n-button>
						<n-button type="warning" @click="deletePhoto">Delete</n-button>
					</n-space>
				</template>
			</n-card>
		</n-modal>

		<n-modal
			v-model:show="showChangeOCRModal"
			:mask-closable="true" >
			<n-card
				style="width: 400px;"
				title="Change OCR Text"
				:bordered="false"
				role="dialog"
				aria-modal="true"
				>
				
				<n-input
					placeholder="Enter the text on the photo"
					type="textarea"
					v-model:value="current_ocr_text"
					:autosize="{
						minRows: 3,
						maxRows: 5
					}"
				/>
				
				<template #footer>
					<n-space justify="end">
						<n-button @click="showChangeOCRModal=false">Cancel</n-button>
						<n-button type="success" @click="changeOCRText">Change Text</n-button>
					</n-space>
				</template>
			</n-card>
		</n-modal>
	</div>
</template>

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

import PhotoItem from '@/components/PhotoItem'
import PhotoCropper from '@/components/PhotoCropper'

export default {
	components: {
		PhotoItem,
		PhotoCropper,
	},
	setup() {
		useMeta({ title: 'Manage Photos' })
		const message = useMessage()
		return { message }
	},
	data() {
		return {
			current_photo: null,
			current_photo_intersections: null,

			showChangeGroupModal: false,
			showCropModal: false,
			showChangeOCRModal: false,
			showDeleteModal: false,

			new_group: null,
			current_ocr_text: '',
			current_photo_src: null,

			is_group_loading: new Map(),
		}
	},
	computed: {
		photoGroups() {
			let groups = this.$store.state.photoGroups
			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 []
		},
		photos() {
			return this.$store.state.photos
		},
		groups_select_options() {
			if (this.photoGroups.length > 0) {
				let options = []
				for (const idx in this.photoGroups) {
					options.push({
						value: this.photoGroups[idx].id,
						label: this.photoGroups[idx].name,
					})
				}
				return options
			}
			return []
		},
	},
	mounted() {
		this.$store.dispatch('loadPhotoGroups').catch((error) => {
			this.message.error('Cannot load photo groups: ' + error)
		})
	},
	methods: {
		loadPhotosInGroup(group_data) {
			this.is_group_loading.set(group_data.name, true)
			if (group_data.expanded)
				this.$store.dispatch('loadPhotosInGroup', group_data.name)
					.finally(() => this.is_group_loading.set(group_data.name, false))
		},
		getPhotoSrcById(photo_id){
			for (const index in this.photos) {
				let group = this.photos[index]
				let photo = group.filter((photo) => photo.id == photo_id)
				if (photo.length > 0) {
					photo = photo[0]
					return photo.cropped_image !== null ? photo.cropped_image : photo.original_image
				}
			}
			return null
		},
		change_group_modal(photo_id) {
			this.current_photo = photo_id
			this.showChangeGroupModal = true
			this.new_group = this.$store.getters.photoById(photo_id).group
		},
		change_crop_modal(photo_id) {
			this.current_photo = photo_id
			this.showCropModal = true
			let photo = this.$store.getters.photoById(photo_id)
			this.current_photo_src = photo.original_image
			this.current_photo_intersections = photo.intersections
		},
		change_ocr_modal(photo_id) {
			this.current_photo = photo_id
			this.showChangeOCRModal = true
			this.current_ocr_text = this.$store.getters.photoById(photo_id).ocr_text
			if (this.current_ocr_text == null) {
				this.current_ocr_text = ''
			}
		},
		change_delete_modal(photo_id) {
			this.current_photo = photo_id
			this.showDeleteModal = true
		},
		changePhotoGroup(){
			if (this.new_group && this.current_photo) {
				this.$store.dispatch('updatePhoto', {
					id: this.current_photo,
					group: this.new_group
				}).then(()=>{
					this.current_photo = null
					this.new_group = null
					this.showChangeGroupModal = false
				})
			}
		},
		changeCrop() {
			let results = this.$refs.cropper.getResult()
			let bbox = results.bbox
			let rotate = results.rotate
			if (bbox && this.current_photo) {
				this.$store.dispatch('updatePhoto', {
					id: this.current_photo,
					bbox_coords: bbox,
					rotate: rotate
				}).then(()=>{
					setTimeout(()=>{
						this.$store.dispatch('cropPhoto', {
							id: this.current_photo,
							mode: 'bbox'
						}).then(()=>{
							this.current_photo = null
							this.showCropModal = false
						})
					}, 100)
				})
			}
		},
		changeOCRText(){
			if (this.current_ocr_text.length !== null && this.current_photo) {
				this.$store.dispatch('updatePhoto', {
					id: this.current_photo,
					ocr_text: this.current_ocr_text
				}).then(()=>{
					this.current_photo = null
					this.current_ocr_text = null
					this.showChangeOCRModal = false
				})
			}
		},
		deletePhoto(){
			if (this.current_photo) {
				this.$store.dispatch('deletePhoto', this.current_photo).then(()=>{
					this.current_photo = null
					this.showDeleteModal = false
				})
			}
		}
	},
}
</script>

<style scoped>
</style>