<!--
  -   This file is a part of the SteamWar software.
  -
  -   Copyright (C) 2023 SteamWar.de-Serverteam
  -
  -   This program is free software: you can redistribute it and/or modify
  -   it under the terms of the GNU Affero General Public License as published by
  -   the Free Software Foundation, either version 3 of the License, or
  -   (at your option) any later version.
  -
  -   This program is distributed in the hope that it will be useful,
  -   but WITHOUT ANY WARRANTY; without even the implied warranty of
  -   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  -   GNU Affero General Public License for more details.
  -
  -   You should have received a copy of the GNU Affero General Public License
  -   along with this program.  If not, see <https://www.gnu.org/licenses/>.
  -->

<script lang="ts">
    import {createEventDispatcher} from "svelte";
    import {schemRepo} from "@repo/schem.ts";
    import SWModal from "@components/styled/SWModal.svelte";
    import {t} from "astro-i18n"

    const dispatch = createEventDispatcher();

  interface Props {
    open?: boolean;
  }

  let { open = $bindable(false) }: Props = $props();

    async function upload() {
        if (uploadFile == null) {
            return
        }
        let file = uploadFile[0];

        let name = file.name;

        let type = name.split(".").pop();

        if (type !== "schem" && type !== "schematic") {
            return
        }

        let content = await file.arrayBuffer();

        // @ts-ignore
        let b64 = btoa(String.fromCharCode.apply(null, new Uint8Array(content)));

        await $schemRepo.uploadSchematic(name, b64);

        open = false;
        uploadFile = null;
        dispatch("reset")
    }

    let uploadFile: FileList | null = $state(null);
</script>

<SWModal title={t("dashboard.schematic.title")} bind:open>
    <form>
        <input type="file" bind:files={uploadFile} />
    </form>
    {#snippet footer()}
  
          <button class="btn !ml-auto" onclick={upload}>{t("dashboard.schematic.upload")}</button>
          <button class="btn btn-gray" onclick={() => open = false}>{t("dashboard.schematic.cancel")}</button>
      
  {/snippet}
</SWModal>