template>
	<span id="outer" :style="outerStyle" @click="toggleActive">
		<img id="img1" v-bind:src="node.attrs.src" style=" width: 100%;"/>
		<span id="handle" :style="handleStyle" @mousedown.prevent="handleMouseDown($event)"></span>
	</span>
</template>

<script>

export default {
	props: ['node', 'view', 'getPos'],
	data: function() {
		return {
			active: false
		}
	},
	computed: {
		outerStyle() {
			return `position: relative; 
					width:` + this.node.attrs.width + `;
					display: inline-block;
					lineHeight: 0;
					`
		},
		handleStyle() {
			return `position: absolute; 
					bottom: 0px;
					right: opx;
					width: 10px;
					height: 10px;
					border: 3px solid black;
					borderTop: none;
					borderLeft: none;
					display: none;
					cursor: nwse-resize;`
		},
	},
	methods: {
		handleMouseDown(e) {
			const startX = e.pageX
			const startY = e.pageY
			
			const outer = document.getElementById('outer')

			// dont need this because we use px and not em's
			//const fontSize = parseFloat(getComputedStyle(outer).fontSize)
			const startWidth = parseFloat(this.node.attrs.width.match(/(.+)px/)[1])
			
			const onMouseMove = (e) => {
				const currentX = e.pageX
				const currentY = e.pageY

				const diffInPx = currentX - currentY
				outer.style.width = `${startWidth + diffInPx}px`
			}

			const onMouseUp = (e) => {
				e.preventDefault()

				document.removeEventListener("mousemove", onMouseMove)
				document.removeEventListener("mouseup", onMouseUp)
				
				const transaction = this.view.state.tr.setNodeMarkup(this.getPos(),
						null, {src: this.node.attrs.src, width: outer.style.width}).setSelection(this.view.state.selection)
				
				this.view.dispatch(transaction)
			}

			document.addEventListener("mousemove", onMouseMove)
			document.addEventListener("mouseup", onMouseUp)

		},
		toggleActive() {
			// console.log("flip")
			this.active = !this.active
		}

	},
	watch: {
			active: function() {
			// console.log("hejs")
			const handle = document.getElementById("handle")
			const img = document.getElementById("img1")

			// We have clicked the image 
			if(this.active) {
				img.classList.add("ProseMirror-selectednode")
				handle.style.display = ""
			} else { // we havent clicked the image
				img.classList.remove("ProsseMirror-selectednode")
				handle.style.display = "none"
			}
		}
	}
}
</script>

<style>
</style>