<script>
  import { onMount } from 'svelte'

  import { DB } from '../../shared/db'
  import { getSettingsWithDefaults } from '../../shared/lib'
  import { notify } from '../toasts'

  let settings = null

  async function load() {
    settings = await getSettingsWithDefaults()
  }

  async function save() {
    for (const [key, value] of Object.entries(settings)) {
      await DB.settings.put({ key, value })
    }
    notify('Saved')
  }

  onMount(load)
</script>

<h2 class="mt-8 text-2xl">Settings</h2>
{#if settings}
  <form class="mt-2" on:submit|preventDefault={save}>
    <div class="form-group">
      <label class="form-label">
        Retention
        <small>(Days)</small>
        <input class="form-input" type="number" min="3" max="365" step="1" bind:value={settings.retention} />
      </label>
      <label class="form-label">
        Idle Timeout
        <small>(Minutes)</small>
        <input class="form-input" type="number" min="0" step="1" bind:value={settings.idleTimeout} />
        <p>Stop tracking after a certain period of idle behavior. <span class="font-mono">0</span> to disable.</p>
      </label>

      <div class="mt-2">
        <button type="submit" class="btn btn-primary">Save</button>
      </div>
    </div>
  </form>
{:else}
  <div class="loading loading-lg" />
{/if}
