<template>

    <form v-if="editing" class="edit">
    <textarea v-model="style"></textarea>
    <button @click="edit">Confirm</button>
    <button @click.prevent="remove"> X </button>
    </form>


    <svg ref="container" id="container" @mousedown="startDrawing" @mousemove="moveDrawing" @mouseup="stopDrawing">
        <path 
            v-for="(p, index) in paths" 
            :key="p.path" 
            :d="p.path" 
            :style="p.style" 
            stroke-width="1px" 
            stroke="currentColor"
            fill="none"
            @click="select(p, index)"
        />

    </svg>

</template>

<script setup>

import {ref, computed, onMounted} from 'vue'

let style = ref("color: white; fill: white; stroke-width: 4px;")
const editing = ref(false)
const currentIndex = ref(0)

const edit = () => {
    paths.value[currentIndex.value].style = style.value
    currentIndex.value = null
    editing.value = false;
}

const select = (p, index) => {
    editing.value = true
    currentIndex.value = index
    if (p.style != "") {
        style.value = p.style
    }
}

const remove = () => {
    paths.value.splice(currentIndex.value, 1)
    editing.value = false
}

const container = ref(null)
const paths = ref([])
let rect = null
let path = null
let strPath = "" 
let buffer = []
const bufferSize = 10

const width = ref(0)
const height = ref(0)

const setViewBox = () => container.value.setAttribute('viewBox', `0 0 ${container.value.clientWidth} ${container.value.clientHeight}`)


class Drawing {
    path = ""
    style = "color: white; stroke-width: 4px;"

    constructor (path) {
        this.path = path
    }

}


onMounted(()=>{
    width.value = container.value.clientWidth
    height.value = container.value.clientHeight
    rect = container.value.getBoundingClientRect()
    setViewBox()
    window.addEventListener("resize", ()=> setViewBox())
})


const getMousePosition = (e) => {
        return {
		x: e.pageX - rect.left,
		y: e.pageY - rect.top
        }
    }

const appendToBuffer = (pt) => {
    buffer.push(pt);
	while (buffer.length > bufferSize) {
		buffer.shift();
	}
}

// Calculate the average point, starting at offset in the buffer
const getAveragePoint = function (offset) {
	var len = buffer.length;
	if (len % 2 === 1 || len >= bufferSize) {
		var totalX = 0;
		var totalY = 0;
		var pt, i;
		var count = 0;
		for (i = offset; i < len; i++) {
			count++;
			pt = buffer[i];
			totalX += pt.x;
			totalY += pt.y;
		}
		return {
			x: totalX / count,
			y: totalY / count,
		};
	}
	return null;
};

const updateSvgPath = function () {
	var pt = getAveragePoint(0);

	if (pt) {
		// Get the smoothed part of the path that will not change
		strPath += " L" + pt.x + " " + pt.y;

		// Get the last part of the path (close to the current mouse position)
	// This part will change if the mouse moves again
		var tmpPath = "";
		for (var offset = 2; offset < buffer.length; offset += 2) {
			pt = getAveragePoint(offset);
			tmpPath += " L" + pt.x + " " + pt.y;
		}

		// Set the complete current path coordinates
		paths.value[paths.value.length-1].path = strPath + tmpPath;
	}
};



const startDrawing = (e) => {

    buffer = []
    let pt = getMousePosition(e)
    appendToBuffer(pt)
    strPath =  "M" + pt.x + " " + pt.y
    
    path = new Drawing(strPath)
    paths.value.push(path)

}

const moveDrawing = (e) => {
    if (!path) return
    appendToBuffer(getMousePosition(e))
    updateSvgPath()
}

const stopDrawing = (e) => {
    if (!path) return
    path = null
    strPath = ""
	paths.value[paths.value.length-1].style += " fill: white;"
}



</script>

<style>
#container {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;

    background: black;
}

path {
    color: white;
    pointer-events: all;
    cursor: pointer;

}

.edit {
    color: white;
    position: absolute;
    padding: 32px;
    z-index: 10000;
}

.edit textarea {
    background: none;
    color: white;
    border: none;
    display: block;
    font-size: 24px;

    line-height: 1.4;
    margin-bottom: 32px;
    width: 500px;
    border-left: 1px solid white;
    padding-left: 1ch;
}

.edit button {
    background: none;
    border: 1px solid white;
    color: white;
    font-size: 16px;
    border-radius: 50%;
    padding: 8px 16px;
    font-weight: bold;
    cursor: pointer;
}

.edit button + button {
    margin-left: 8px;
}

.edit button:hover {
    background-color: white;
    color: black;
}


</style>
