<script>
	import { onMount } from 'svelte';

	import LineEditor from '../../Components/LineEditor.svelte';

	import { useTinyRouter } from 'svelte-tiny-router';
	import { api, get, post } from '../../urls.svelte';
	import { error, yikes } from '../../warn.svelte';
	import { t } from '../../translations.svelte';
    import { user }          from '../../user.svelte.js';

	let polls = $state([]);
	let router = useTinyRouter();

	async function create_poll(name){
		const url = api('poll');
		const res = await post(url,{name});
		if (res.ok) {
			yikes();
			const json = await res.json();
			polls.push(json);
		}
		error(res);
	}

	function edit(poll){
		router.navigate(`/poll/${poll.id}/edit`);
	}

	function evaluate(poll){
		router.navigate(`/poll/${poll.id}/evaluate`);
	}

	async function load(){
		let url = api('poll/list');
		let res = await get(url);
		if (res.ok){
			polls = await res.json();
			yikes();
		} else error(res);
	}

	function open(poll){
		router.navigate(`/poll/${poll.id}/view`);
	}

	function share(poll){
		router.navigate(`/poll/${poll.id}/share`);
	}

	onMount(load);

</script>

<fieldset>
	<legend>{t('polls')}</legend>
	<table>
		<thead>
			<tr>
				<th>{t('name')}</th>
				<th>{t('description')}</th>
				<th>{t('owner')}</th>
				<th>{t('actions')}</th>
			</tr>
		</thead>
		<tbody>
			{#each polls as poll}
			<tr>
				<td onclick={e => open(poll)}>{poll.name}</td>
				<td>{@html poll.description.rendered}</td>
				<td onclick={e => open(poll)}>{poll.owner.name}</td>
				<td>
					{#if user.id == poll.owner.id || poll.permission[user.id].permission == 2}
					<button onclick={e => edit(poll)}>{t('edit')}</button>
					{/if}
					{#if user.id == poll.owner.id || poll.permission[user.id].permission > 0}
					<button onclick={e => evaluate(poll)}>{t('evaluate')}</button>
					{/if}
					<button onclick={e => share(poll)}>{t('share')}</button>
				</td>
			</tr>
			{/each}
			<tr>
				<td>
					<LineEditor simple={true} onSet={create_poll}/>
				</td>
				<td colspan="3">{t('Enter name to create new')}</td>
			</tr>
		</tbody>
	</table>
</fieldset>