<template>
	<div :draggable="draggable" @dragstart="onDragstart" ref="playerContainer" :style="style"
	     @mouseenter="onMouseEnter"
	     @mouseleave="onMouseLeave"
	>

	</div>
</template>

<script>
	import {mapActions} from 'vuex';
	import {Player} from 'svgaplayerweb';

	export default {
		name: "SvgaPreviewView",
		props: {
			maxWidth: {
				type: Number
			},
			maxHeight: {
				type: Number
			},
			src: {
				type: String
			},
			draggable: {
				type: Boolean,
				default: false,
			},
			autoplay: {
				type: Boolean,
				default: false,
			},
		},
		data() {
			return {
				videoSize: {
					width: 0,
					height: 0,
				}
			}
		},
		computed: {
			style() {
				const {width, height} = this.videoSize;
				return {
					width: (this.maxWidth || width) + 'px',
					height: (this.maxHeight || height) + 'px',
				}
			},
			size() {
				const {width, height} = this.videoSize;
				return `${width}x${height}`;
			},
		},
		watch: {
			src(v, oldv) {
				if(v !== oldv){
					this.update();
				}
			}
		},
		mounted() {
			let container = this.$refs.playerContainer;

			this.player = new Player(container);

			this.update();
		},
		methods: {
			onDragstart(e){
				this.$emit('dragstart', e);
			},
			async update() {
				const player = this.player;
				player.clear();

				if(this.src){
					let videoItem = await this.loadSvga(this.src);

					this.videoSize.width = videoItem.videoSize.width;
					this.videoSize.height = videoItem.videoSize.height;
					this.$nextTick(() => {
						player.setVideoItem(videoItem);
						if(this.autoplay){
							player.startAnimation();
						}else{
							player.stepToFrame(0);
						}
					});
				}
			},
			onMouseEnter(){
				if(!this.autoplay){
					this.player.stepToFrame(0, true);
				}
			},
			onMouseLeave(){
				if(!this.autoplay){
					this.player.stepToFrame(0);
				}
			},
			...mapActions([
				'loadSvga'
			]),
		}
	}
</script>

<style scoped>

</style>