<script lang="ts">
    import {Button, Modal} from "flowbite-svelte";
    import type {ExtendedEvent} from "../../../../types/event.js";
    import FightEditPart from "../../../components/FightEditPart.svelte";
    import {fightRepo} from "../../../../repo/repo.js";
    import type {CreateFight} from "../../../../repo/fight.ts";
    import ErrorModal from "../../../components/ErrorModal.svelte";
    import {createEventDispatcher} from "svelte";
    import moment from "moment";

    let dispatch = createEventDispatcher();

    export let open: boolean = false;
    export let data: ExtendedEvent;

    let blueTeam: string = "";
    let redTeam: string = "";

    let start: string = "";

    let gamemode: string = "";
    let map: string = "";

    let kampfleiter: string | null = null;
    let group: string | null = null;
    let groupSearch = "";

    let errorOpen = false;
    let error: Error | null = null;

    $: canCreate = blueTeam !== "" && redTeam !== "" && start !== "" && gamemode !== "" && map !== "";

    async function create() {
        try {
            open = false;
            let res = await $fightRepo.createFight(data.event.id, {
                spielmodus: gamemode,
                blueTeam: parseInt(blueTeam),
                redTeam: parseInt(redTeam),
                start: moment(start),
                map,
                kampfleiter: parseInt(kampfleiter),
                group,
            });
            reset()

            dispatch("create")
        } catch (e) {
            error = e;
            errorOpen = true;
            reset()
        }
    }

    function reset() {
        blueTeam = "";
        redTeam = "";
        start = "";
        gamemode = "";
        map = "";
        kampfleiter = "";
        group = null;
        groupSearch = "";
    }
</script>

<Modal bind:open outsideclose title="Create Fight" on:hide={reset}>
    <div class="text-center">
        <FightEditPart
                bind:blueTeam
                bind:redTeam
                bind:start
                bind:kampfleiter
                bind:gamemode
                bind:map
                bind:group
                bind:groupSearch
                teams={data.teams}
        />
    </div>
    <svelte:fragment slot="footer">
        <Button on:click={create} class="mr-auto" disabled={!canCreate}>Create</Button>
        <Button color="light" on:click={() => open = false}>Cancel</Button>
    </svelte:fragment>
</Modal>

<ErrorModal bind:open={errorOpen} bind:error={error} on:close={() => errorOpen = false}/>
