<script setup>
import Papa from 'papaparse'

const supabase = useSupabaseClient()

const accounts = (supabase.from("bankAccounts").select()).data

let items = ref([])
async function readSingleFile(evt) {
  var f = document.getElementById('fileInput').files[0];
  if (f) {
    let results = []
    let text = await f.text()
    results = Papa.parse(text).data
    console.log(results[0])
    results = results.slice(1)
    results = results.map(temp => {
      return {
        iban: temp[1],
        bank: temp[3],
        date: temp[4],
        partnerName: temp[6],
        partnerIban: temp[7],
        type: temp[9],
        text: temp[10],
        value: temp[11],
        currency: temp[12]
      }
    })

    console.log(results)
    items.value = results

    parseStatements()

  } else {
    alert("Failed to load file");
  }
}

const newStatements = ref([])

const parseStatements = async () => {
  items.value.forEach(item => {
    if(item.date) {
      let returnObj = {
        date: item.date,
        partnerIban: item.partnerIban,
        partnerName: item.partnerName,
        text: item.text,
        value: Number(item.value.replace(",",".")),

      }

      newStatements.value.push(returnObj)
    }

  })

  const {data,error} = await supabase
      .from("bankStatements")
      .insert(newStatements.value)
      .select()

  console.log(data)
  console.log(error)

}


</script>

<template>
<div>
  <UInput
    type="file"
    id="fileInput"
  />
  <UButton
    @click="readSingleFile"
  >Test</UButton>

  <table>
    <tr
      v-for="temp in items"
    >
      <td>{{temp.date}}</td>
      <td>{{temp.partnerName}}</td>
      <td>{{temp.text}}</td>
      <td>{{temp.value}}</td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </table>


</div>
</template>

<style scoped>

</style>