<div class="columns">
  <div class="column is-two-thirds">
    {#each Object.entries(schueler) as [klasse, schueler]}
      <h3 class="title">{klasse}</h3>
      <table class="table is-striped">
        <thead>
          <tr>
            <th>Name</th>
            <th>Vorname</th>
            <th>Voucher</th>
          </tr>
        </thead>
        <tbody>
          {#each schueler as s}
            <tr>
              <td>{s.Name}</td>
              <td>{s.Vorname}</td>
              <td><span class={s.voucher && "tag is-info is-medium"}>{s.voucher || ''}</span></td>
            </tr>
          {/each}
        </tbody>
      </table>
    {/each}
  </div>
  <div class="column">
    <h3 class="title">Voucher austauschen</h3>
    <div class="field">
      <label class="label">
        Voucher als Liste zeilenweise in das Textfeld einfügen. Alte Voucher
        werden entfernt und durch die neuen ersetzt.
      </label>
      <div class="control">
        <textarea class="textarea" bind:value={vouchers} rows="10" cols="20"></textarea>
      </div>
    </div>
    <div class="field is-grouped">
      <div class="control">
        <button class="button is-link" on:click={()=>update_vouchers()}>Aktualisieren</button>
      </div>
    </div>
  </div>
</div>

<script>
  export let schueler, klasse, privat
  const { Pool } = R('pg')
  const pool = new Pool({ connectionString: privat.mein_bk_db})
  let vouchers = ''
  function vouchers_value () {
    const arr = vouchers.split(/\r\n|\r|\n/g)
    return arr.filter(e=>!e.startsWith('#')).map(e=>'(\'' + e.substring(2,13) + '\')').join(',')
  }
  const update_vouchers = async () => {
    const query = `INSERT INTO wlan (voucher)
                   VALUES ${vouchers_value()}
                   RETURNING *`
    // const values = [vouchers_value()]
    try {
      await pool.query(`DELETE FROM wlan`)
      const res = await pool.query(query)
      console.log(res.rows)
    } catch(err) {
      console.log(err.stack)
    }
  }
</script>
