<script lang="ts">
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';
	import { createParcours, getParcours, updateParcours } from '../../requests/room.request';
	import { getContext, onMount } from 'svelte';
	import { writable, type Writable } from 'svelte/store';
	import ExerciceSelector from '../exos/ExerciceSelector.svelte';
	import InputWithLabel from '../forms/InputWithLabel.svelte';
	import type { ExoSelect, Member, ParcoursRead, Room } from 'src/types/room.type';

	export let id_code: string | null = null;

	const room = getContext<Writable<Room | null>>('room');
	const member = getContext<Writable<Member | null>>('member');
	const parcours = getContext<Writable<ParcoursRead | null>>('parcours');
	const {send} = getContext<{send: Function}>('ws');

	const { error, success } = getContext<{ error: Function; success: Function }>('notif');
	const { isAuth } = getContext<{ isAuth: Writable<boolean> }>('auth');
	const exos: Writable<ExoSelect[]> = writable(
		id_code != null &&$parcours != null ? ($parcours.exercices as ExoSelect[]) : []
	);

	let name = id_code != null &&$parcours != null ? $parcours.name : '';
	let time = id_code != null &&$parcours != null ? String($parcours.time) : '10';
	let max_mistakes =id_code != null && $parcours != null ? String($parcours.max_mistakes): '5';

	onMount(() => {
		if ($parcours == null && id_code != null && $room != null && $member != null) {
			getParcours($room.id_code, id_code, $member.isUser ? $member.clientId : null).then((p) => {
				parcours.set(p);
				exos.set(p.exercices as ExoSelect[]);
				name = p.name;
				time = p.time;
				max_mistakes = p.validate_condition;
			});
		}
	});
</script>

<div class="create">
	<div class="exos">
		<ExerciceSelector {exos} />
	</div>
	<form
		class="options"
		on:submit|preventDefault={() => {
			if (!$room) return;
			if ($parcours == null || id_code== null) {
				createParcours(
					$room?.id_code,
					{
						time: parseInt(time),
						name,
						max_mistakes: parseInt(max_mistakes),
						exercices: [
							...$exos.map((e) => {
								return {
									exercice_id: e.exercice_id,
									quantity: typeof e.quantity != 'number' ? parseInt(e.quantity) : e.quantity
								};
							})
						]
					},
					!$isAuth ? $member?.clientId : null
				).then((r)=>{
					parcours.set(r)
					$page.url.searchParams.set('p', r.id_code);
					send("sub_parcours", {"parcours_id": r.id_code})
					goto(`?${$page.url.searchParams.toString()}`);

				}).catch((r) => {
					error('Echec lors de la création du parcours', `Raison: ${r.detail}`);
				});
			} else if($parcours != null && $parcours.id_code == id_code){
				updateParcours(
					$room?.id_code,
					$parcours.id_code,
					{
						time: parseInt(time),
						name,
						max_mistakes: parseInt(max_mistakes),
						exercices: [
							...$exos.map((e) => {
								return {
									exercice_id: e.exercice_id,
									quantity: typeof e.quantity != 'number' ? parseInt(e.quantity) : e.quantity
								};
							})
						]
					},
					!$isAuth ? $member?.clientId : null
				)
					.then((r) => {

						parcours.set(r);
						$page.url.searchParams.delete('edit');

						goto(`?${$page.url.searchParams.toString()}`);

					})
					.catch((r) => {

						error('Echec lors de la modification du parcours', `Raison: ${r.detail}`);
					});
			}
		}}
	>
		<h1>Nouveau parcours</h1>
		<InputWithLabel label="Nom" bind:value={name} required min="5" autofocus/>
		<InputWithLabel label="Temps (min)" bind:value={time} type="number" />
		<InputWithLabel label="Nombre maximum de fautes" bind:value={max_mistakes} type="number" />
		<div class="btns">
			<button class="primary-btn">Valider</button>
			<button
				class="danger-btn"
				on:click|preventDefault={() => {
					if ($parcours != null && id_code !=null) {
						$page.url.searchParams.delete('edit');
						goto(`?${$page.url.searchParams.toString()}`);
						return
					}

					$page.url.searchParams.delete('p');
					goto(`?${$page.url.searchParams.toString()}`);

				}}>Annuler</button
			>
		</div>
	</form>
</div>

<style lang="scss">
	@import "../../mixins.scss";
	.create {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		column-gap: 30px;
		height: 100%;
		@include down(800){
			display: flex;
			flex-direction: column;
			gap: 20px;
			padding: 13px;
		}
	}

	.options {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20px;
		margin-top: 30px;
	}
</style>
