<div class="field is-horizontal">
  <div class="field-body">
    <div class="field">
      <p class="control is-expanded has-icons-left">
        <label class="label is-small">Beginn der Prowo-Wahl</label>
        <input type="datetime-local" bind:value={wahlbeginn_prowo} class="input is-small">
      </p>
    </div>
    <div class="field">
      <p class="control is-expanded has-icons-left">
        <label class="label is-small">Ende der Prowo-Wahl</label>
        <input type="datetime-local" bind:value={wahlende_prowo} class="input is-small">
      </p>
    </div>
  </div>
</div>
<div class="field">
  <p class="control is-expanded has-icons-left">
    <label class="label is-small">Thema der Prowo</label>
    <input type="text" bind:value={thema_prowo} class="input is-expanded is-small">
  </p>
</div>
<div class="field">
  <button class="is-small button is-default" on:click={changeDate}> Wahlzeitraum ändern </button>
  {#if check}<span class="tag is-success">✓</span>{/if}
</div>

<script>
  export let schueler, privat, einstellungen = {}
  let check
  const { Pool } = R('pg')
  const pool = new Pool({ connectionString: privat.mein_bk_db})
  let wahlbeginn_prowo = setDateTime(einstellungen.wahlbeginn_prowo)
  let wahlende_prowo = setDateTime(einstellungen.wahlende_prowo)
  let thema_prowo = einstellungen.thema_prowo || ''
  const changeDate = async _ => {
    const query = `UPDATE einstellungen
                   SET wahlbeginn_prowo=$1, wahlende_prowo=$2, thema_prowo=$3
                   RETURNING wahlbeginn_prowo, wahlende_prowo, thema_prowo`
    const values = [new Date(wahlbeginn_prowo), new Date(wahlende_prowo), thema_prowo]
    try {
      const res = await pool.query(query, values)
      const data = res.rows[0]
      console.log(res)
      einstellungen.wahlbeginn_prowo = data.wahlbeginn_prowo
      einstellungen.wahlende_prowo = data.wahlende_prowo
      einstellungen.thema_prowo = data.thema_prowo
      einstellungen = einstellungen
      check = true
    } catch(err) {
      console.log(err.stack)
    }
  }

  function setDateTime (date) {
    if (!date) return
    const d = new Date(date)
    return d.toISOString().replace('Z','')
  };
</script>