<script lang="ts">
	import MdClose from 'svelte-icons/md/MdClose.svelte';
	import MdEdit from 'svelte-icons/md/MdEdit.svelte';
	import MdDelete from 'svelte-icons/md/MdDelete.svelte';
	import { getContext, setContext } from 'svelte';
	import DownloadForm from './DownloadForm.svelte';
	import EditForm from './EditForm.svelte';
	import type { Exercice, Page, Tag } from '../../types/exo.type';
	import type { Writable } from 'svelte/store';
	import type { Store } from '../../types/api.type';
	export let exo: Exercice;
	export let exos: Writable<Store<Page>>;
	export let tags: Writable<Store<Tag[]>>;
	setContext("tags", tags)
	let editing = false;

	const updateExo = (e: Exercice) => {
		exos.update((o) => {
			return {
				...o,
				data: {
					...o.data,
					items: [
						...o.data.items.map((ex) => {
							if (ex.id_code == exo.id_code) {
								return e;
							} return ex;
						})
					]
				}
			};
		});
	};

</script>

<div class="modal">
	{#if editing === false}
		<DownloadForm
			{exo}
			delete_={() => {
				exos.update((o) => {
					return {
						...o,
						data: { ...o.data, items: [...o.data.items.filter((e) => e.id_code != exo.id_code)] }
					};
				});
			}}
			edit={() => {
				editing = true;
			}}
		/>
	{:else if editing === true}
		<h1>Modification</h1>
		<EditForm
			bind:exo
			cancel={() => {
				editing = false;
			}}
			{updateExo}
		/>
	{/if}
</div>

<style lang="scss">
	@import '../../variables';
	@import '../../mixins';

	.modal {
		min-width: 800px;
		background: $background;
		padding: 70px;
		grid-gap: 10px;
		position: relative;
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		gap: 20px;
		@include down(800){
			width: 100%;
			height: 100%;
			min-width: 0;
			padding: 50px;
		}
	}

	h1{
		font-size: 1.8rem;
	}
</style>
