<template>
	<el-popover
		placement="top"
		trigger="hover"
		width="auto"
		:disabled="!legalUrl"
		:content="url"
		class="source-input"
		popper-class="source-input-popover"
	>
		<div class="wrapper">
			<img style="max-width: 200px;" class="thumbnail alpha-image-background" v-if="!url.endsWith('.svga')" :src="url" alt=""/>
			<svga-preview-view :max-width="200" class="thumbnail alpha-image-background" :max-height="200" v-if="url.endsWith('.svga')" :src="url" alt=""/>
			<span>{{assetSize(url)}}</span>
		</div>
		<el-input slot="reference" :disabled="!editable" v-model="editValue" controls-position="right" :placeholder="defaultValue"
		          @change="onChange" @drop.native="drop" @dragover.native="dragOver">
			<el-button slot="append" icon="el-icon-aim" @click="locateAsset"></el-button>
		</el-input>
	</el-popover>
</template>

<script>
	import {mapGetters} from 'vuex'
	import LinkableInputWrapper from "./LinkableInputWrapper";
	import CmdInputWrapper from "./CmdInputWrapper";
	import {assetScheme, getInputDefaultValue} from "../../utils";
	import events from "@/global-events.js"
	import SvgaPreviewView from "../SvgaPreviewView";

	export default {
		name: "SourceInput",
		components: {SvgaPreviewView, LinkableInputWrapper, CmdInputWrapper},
		props: ['value', 'container', 'property', 'propertyName', 'editable'],
		data(){
			return {
				editValue: this.getEditValue(),
			}
		},
		mounted(){
			this.editValue = this.getEditValue();
		},
		watch:{
			value(){
				this.editValue = this.getEditValue();
			}
		},
		computed: {
			defaultValue(){
				return getInputDefaultValue(this.property);
			},
			url: function () {
				if (this.value) {
					if (this.value.startsWith(assetScheme)) {
						let uuid = this.value.replace(assetScheme, '');
						let _ass = this.assets.find(a => a.uuid === uuid);
						return _ass ? _ass.url : '';
					} else {
						return this.value;
					}
				} else {
					return '';
				}
			},
			legalUrl: function () {
				return this.value && this.value.startsWith(assetScheme);
			},
			...mapGetters(['assets', 'assetSize']),
		},
		methods: {
			getEditValue() {
				return this.value === undefined ? this.property.default : this.value;
			},
			onChange(v) {
				if(v !== this.value){
					this.$emit('input', v, this.container, this.propertyName, this.value);
				}
			},
			drop(e) {
				if (this.$store.state.project.dragUUID) {
					console.log('native drop', this.$store.state);
					this.editValue = assetScheme + this.$store.state.project.dragUUID;
					this.onChange(this.editValue)
				}
			},
			dragOver(e) {
				if(this.editable){
					e.preventDefault();
				}
			},
			locateAsset() {
				let uuid = this.value ? this.value.replace(assetScheme, '') : null;
				if (uuid) {
					let asset = this.assets.find(a => a.uuid === uuid);
					if (asset) {
						events.$emit('select-asset-item', asset);
					}
				}
			},
		},
	}
</script>

<style scoped>

</style>