<script>
  import { saveAs } from 'file-saver'
  import dj from 'dayjs'

  import FileUpload from '../components/FileUpload.svelte'

  import { clear, DB } from '../../shared/db'
  import { longPress } from '../../shared/lib'
  import { notify } from '../toasts'

  let file
  let loading = false

  async function exportDB() {
    try {
      loading = true
      const blob = await DB.export()
      const filename = `Ora [${dj().format('YYYY-MM-DD HH-mm-ss')}].json`
      saveAs(blob, filename)
      notify('Exported')
    } finally {
      loading = false
    }
  }

  async function clearDB() {
    await clear()
    window.location.reload()
  }

  async function importDB() {
    try {
      loading = true
      await clear()
      await DB.import(file)
      notify('Imported')
    } catch (e) {
      notify('Error importing', 'error')
    } finally {
      loading = false
    }
  }
</script>

<h2 class="mt-8 text-2xl">Your Data</h2>
<div class="mt-2">
  <FileUpload bind:file />
  <button class="btn btn-primary" class:loading on:click={importDB} disabled={!file}>Import</button>
  <button class="btn btn-primary" class:loading on:click={exportDB}>Export</button>
  <button class="btn btn-error tooltip" class:loading data-tooltip="Hold to delete" use:longPress={clearDB}>
    Delete all data
  </button>
</div>
