<script lang="ts">
    import {Button, Input, Label, Modal, Select} from "flowbite-svelte";
    import moment from "moment";
    import {gamemodes, groups, maps, players} from "../../../../stores/stores.js";
    import type {EventFight, ExtendedEvent} from "../../../../types/event.js";
    import TypeAheadSearch from "../../../components/TypeAheadSearch.svelte";
    import FightEditPart from "../../../components/FightEditPart.svelte";
    import type {UpdateFight} from "../../../../repo/fight.js";
    import {fightRepo} from "../../../../repo/repo.js";
    import ErrorModal from "../../../components/ErrorModal.svelte";
    import {createEventDispatcher} from "svelte";

    export let fight: EventFight;
    export let data: ExtendedEvent;
    export let open = false;

    let redTeam = fight.redTeam.id.toString();
    let blueTeam = fight.blueTeam.id.toString();
    let start = moment(fight.start).utc(true).toISOString().slice(0, -1);
    let kampfleiter = fight.kampfleiter.id.toString();
    let gamemode = fight.spielmodus
    let map = fight.map;
    let group = fight.group;
    let groupSearch = fight.group ?? "";

    let errorOpen = false;
    let error = undefined;

    let dispatch = createEventDispatcher();
    function save() {
        const update: UpdateFight = {
            blueTeam: parseInt(blueTeam), group: group === "" ? null : group, kampfleiter: parseInt(kampfleiter), map: map, redTeam: parseInt(redTeam), spielmodus: gamemode, start: moment(start)
        }

        $fightRepo.updateFight(fight.id, update)
            .then(value => {
                open = false;
                fight = value;
                dispatch("update", value);
            })
            .catch((e) => {
                error = e.message;
                errorOpen = true;
            })
    }
</script>

<Modal title="Edit {fight.blueTeam.name} vs. {fight.redTeam.name}" bind:open outsideclose size="xs">
    <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>
    <div class="flex">
        <Button on:click={save}>Save</Button>
        <Button color="light" class="ml-auto" on:click={() => open = false}>Cancel</Button>
    </div>
</Modal>

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