<script setup>
	import { onMounted, ref } from 'vue'
	import { copiedSongs } from '../libs/state.js'

	const songs = ref([])

	onMounted(async ()=>{
		const response = await fetch(import.meta.env.VITE_PRACTICE_TRACKER_API_URL+'songs')
		songs.value = await response.json()
	})
	const copy = (title) => {
		navigator.clipboard.writeText(title);
	}
	const link = (song) => {
		if(copiedSongs.value.findIndex(copiedSong=>copiedSong.id === song.id) === -1){
			copiedSongs.value.push(song)
		}
	}
	const unlink = (song) => {
		copiedSongs.value = copiedSongs.value.filter(currSong => currSong.id !== song.id)
	}
</script>
<template>
	<h2>Songs</h2>
	<table>
		<thead>
			<tr>
				<th>id</th>
				<th>title</th>
				<th>notes</th>
			</tr>
		</thead>
		<tbody>
			<tr v-for="song in songs">
				<td>{{song.id}}</td>
				<td>
					<a v-bind:name="'/songs/' + song.id">
						{{song.title}}
					</a>
					<br/>
					<button @click="copy(song.title)">Copy</button>
					<button @click="link(song)" v-if="copiedSongs.findIndex(currSong => currSong.id === song.id) === -1">Link</button>
					<button @click="unlink(song)" v-if="copiedSongs.findIndex(currSong => currSong.id === song.id) !== -1">X</button>
				</td>
				<td>{{song.notes}}</td>
			</tr>
		</tbody>
	</table>
</template>

<style scoped>
button {
	padding: 1em 2em;
	margin: 1em;
}
td:nth-child(2){
	text-align:center;
}
</style>
