<template>
  <div>
		<n-space justify="start">
			<cropper
				class="cropper"
				:src="src"
				:stencil-props="aspect_ratio"
				:auto-zoom="true"
				@change="change"
				ref="cropper"
			/>

			<n-space vertical justify="space-between">
				<div>
					<h2>Preview</h2>
					<n-image
						class="preview"
						height="200"
						:src="preview_data_url"
					/>
				</div>

				<n-checkbox v-model:checked="lock_aspect_ratio">lock aspect ratio to flip chart size?</n-checkbox>
			</n-space>
		</n-space>
  </div>
</template>

<script>
import {Cropper} from 'vue-advanced-cropper'
import 'vue-advanced-cropper/dist/style.css'


export default {
	components: {
		Cropper,
	},
	props: {
		src: {
			type: String,
			required: true,
		}
	},
	data() {
		return {
			preview_data_url: null,
			lock_aspect_ratio: true,
			bbox: []
		}
	},
	computed: {
		aspect_ratio() { 
			if (this.lock_aspect_ratio) {
				return {
					aspectRatio: 1/1.41421356
				}
			}
			return {}
		}
	},
	methods: {
		coordinates_to_bbox(coordinates) {
			let top_left = [
				coordinates.left,
				coordinates.top
			]
			let top_right = [
				coordinates.left + coordinates.width,
				coordinates.top
			]
			let bottom_right = [
				coordinates.left + coordinates.width,
				coordinates.top + coordinates.height
			]
			let bottom_left = [
				coordinates.left,
				coordinates.top + coordinates.height
			]

			return [top_left, top_right, bottom_right, bottom_left]
		},
		change({ coordinates, canvas }) {
			this.preview_data_url = canvas.toDataURL()
			this.bbox = this.coordinates_to_bbox(coordinates)
		},
		getResult() {
			return JSON.parse(JSON.stringify(this.bbox))
		}
	}
}
</script>

<style scoped>
.cropper {
	height: 600px;
	width: 600px;
	background: #DDD;
}

.preview {
	max-width: 300px;
}
</style>