<script>
    import Button from "$lib/components/base/Button.svelte";
    import Input from "$lib/components/base/Input.svelte";
    import { onMount } from "svelte";

    let brawlsets = $state([])
    let deckImporter = $state("")
    let selectedBset = $state("")
    let deckName = $state("")
    let deckUrl = $state("")
    let commander = $state("")
    let token = $state("")

    onMount( async () => {
        const storageData = window.localStorage.getItem("pocketbase_auth")
        if (storageData != null) {
          const jsonData = JSON.parse(storageData)
          token = jsonData.token
        }

        fetch("/json/misc/brawlsets")
            .then( response => response.json() )
            .then( data => {
                let sortedData = data
                sortedData.sort((a,b) => a.Name.localeCompare(b.Name))
                brawlsets = sortedData
            })
    })

    function setCommander(txt) {
      let lines = txt.split("\n")
      commander = lines[lines.length - 1].slice(1)
    }
    
    function getDataFromLine(line){
      if(line != "") {
        const data = line.split(" ")
        const amount = parseInt(data[0])
        const name = data.slice(1).join(" ").split(" // ")[0].split("/")[0]
        return {"name":name, "amount":amount}
      } else {
        return null
      }
    }

    function importDeck(){
      const deckText = deckImporter
      let lines = deckText.split("\n")
      lines = lines.filter((line) => line.match(/[0-9]+\s[\w]+/) != undefined)
      const dataToSend = { name: deckName, url: deckUrl, selected_bset:  selectedBset,commander_name: getDataFromLine(commander).name, cards: [] }
      lines.slice(0, lines.length - 1).forEach((line) => {
        const data = getDataFromLine(line)
        if(data != null) {
          dataToSend.cards.push(data)
        }
      });

      console.log(dataToSend)

      fetch('/api/deck/create', {
        method: "POST",
        headers: {Authorization: token, "Content-Type": "application/json"},
        body: JSON.stringify(dataToSend)
      }).then((res) => {
        if(res.status == 200) {
          res.json().then((apiData) => {
            deckImporter = ""
            selectedBset = ""
            deckName = ""
            deckUrl = ""
            commander = ""
            console.log(apiData)
          })
        } else if (res.status == 401) {
          res.json().then((apiData) => {
            console.log(apiData)
          })
        }
      })
    }

</script>

<div class="flex flex-col w-full items-center p-4">
  <div class="flex flex-col-reverse md:flex-row max-w-4xl w-full gap-4">
    <div class="flex flex-col w-full">
      <textarea placeholder="Deck list dans le format MTGO" class="h-60" bind:value={deckImporter} oninput={(e) => setCommander(e.target.value)}></textarea>
      <span>Commandant : {commander}</span>
    </div>
    <div class="flex flex-col w-full gap-4">
      <Input type="text" placeholder="Nom du deck" bind:value={deckName} />
      <Input type="text" placeholder="Url du deck (facultatif)" bind:value={deckUrl} />
      <select bind:value={selectedBset}>
        <option value="0">Selectionnez un Brawlset...</option>
        {#each brawlsets as brawlset}
          <option value={brawlset.SanitizedName}>
            {brawlset.Name}
          </option>
        {/each}
      </select>
      <Button onclick={importDeck}>Importer</Button>
    </div>
  </div>
</div>
