<script>
 import { createEventDispatcher } from 'svelte';
 import { goto } from '$app/navigation';

 import DateTimeInput from './DateTimeInput.svelte';
 import { ToastsStore } from '$lib/stores/toasts';

 const dispatch = createEventDispatcher();
 export let category = null;

 function saveCategory() {
     category.save().then((response) => {
         dispatch('saved', response);
     }, (error) => {
         ToastsStore.addErrorToast({
             msg: error,
         });
     })
 }

 function deleteCategory() {
     category.delete().then((response) => {
         goto(`categories`);
     }, (error) => {
         ToastsStore.addErrorToast({
             msg: error,
         });
     })
 }

 function duplicateCategory() {
     category.duplicate().then((response) => {
         goto(`categories/${response.id}`);
     }).catch((error) => {
         ToastsStore.addErrorToast({
             msg: error,
         });
     })
 }

</script>

<form on:submit|preventDefault={saveCategory}>

    {#if category.id}
        <div class="row">
            <div class="col-sm-3 text-sm-end">
                <label for="cid" class="col-form-label col-form-label-sm">Identifiant de la catégorie</label>
            </div>
            <div class="col-sm-8">
                <input type="text" class="form-control-plaintext form-control-sm" id="cid" value={category.id}>
            </div>
        </div>
    {/if}

    <div class="row">
        <div class="col-sm-3 text-sm-end">
            <label for="title" class="col-form-label col-form-label-sm">Titre de la catégorie</label>
        </div>
        <div class="col-sm-8">
            <input type="text" class="form-control form-control-sm" id="title" bind:value={category.label}>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-3 text-sm-end">
            <label for="promo" class="col-form-label col-form-label-sm">Promo</label>
        </div>
        <div class="col-sm-8 col-md-4 col-lg-2">
            <input type="number" step="1" min="0" max="2068" class="form-control form-control-sm" id="promo" bind:value={category.promo}>
        </div>
    </div>

    <div class="row row-cols-3 mx-1 my-2">
        <div class="form-check">
            <input class="form-check-input" type="checkbox" id="expand" bind:checked={category.expand}>
            <label class="form-check-label" for="expand">
                Étendre par défaut
            </label>
        </div>
    </div>

    <div class="form-group row">
        <div class="col-sm-10">
            <button type="submit" class="btn btn-primary">Enregistrer</button>
            {#if category.id}
                <button type="button" class="btn btn-danger" on:click={deleteCategory}>Supprimer</button>
            {/if}
        </div>
    </div>

</form>
