<div class="columns">
  <div class="column is-two-thirds">
    {#each Object.entries(schueler) as [klasse, schuelers]}
      <h3 class="title">{klasse}</h3>
      <table class="table is-striped">
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Vorname</th>
            <th>Projektwahl</th>
          </tr>
        </thead>
        <tbody>
          {#each schuelers as s}
            <tr>
              <td>{s.hashid}</td>
              <td>{s.Name}</td>
              <td>{s.Vorname}</td>
              <td class={'has-background-'+wahl(s)} on:click={() => modalset(s)} style="cursor: pointer">
                {`Woche: ${s.woche == null ? '–' : s.woche} Mo/Di: ${s.mo_di == null ? '–' : s.mo_di} Mi/Do ${s.mi_do == null ? '–' : s.mi_do}`}
              </td>
            </tr>
          {/each}
        </tbody>
      </table>
    {/each}
  </div>
  <div class="column">
      <h3 class="title">Klassen</h3>
      <table class="table is-striped">
        <thead>
          <tr>
            <th>Klasse</th>
            <th>Woche</th>
            <th>Mo/Di</th>
            <th>Mi/Do</th>
          </tr>
        </thead>
        <tbody>
          {#each klassen as k,i}
            <tr>
              <td>{k.klasse}</td>
              <td class={`has-text-${k.abwesenheit === 0 ? 'danger':'success'}`} style="cursor: pointer;" on:click={() => switcher(i,0)}>{k.abwesenheit === 0 ? '✘':'✔'}</td>
              <td class={`has-text-${k.abwesenheit === 1 ? 'danger':'success'}`} style="cursor: pointer;">{k.abwesenheit === 1 ? '✔':'✘'}</td>
              <td class={`has-text-${k.abwesenheit === 2 ? 'danger':'success'}`} style="cursor: pointer;">{k.abwesenheit === 2 ? '✔':'✘'}</td>
            </tr>
          {/each}
        </tbody>
      </table>
  </div>
</div>

{#if modal_s}
  <div class="modal" class:is-active={modal}>
    <div class="modal-background"></div>
    <div class="modal-card">
      <header class="modal-card-head">
        <p class="modal-card-title">{modal_s.Vorname} {modal_s.Name}</p>
        <button class="delete" aria-label="close" on:click={() => modal = !modal}></button>
      </header>
      <section class="modal-card-body">
        <div class="field is-horizontal">
          <div class="field-label is-normal">
            <label class="label">Woche</label>
          </div>
          <div class="field-body">
            <div class="field is-narrow">
              <div class="control">
                <div class="select is-fullwidth">
                  <select bind:value={selected_woche} on:change={wahl_aendern}>
                    <option value={null}>Kein Projekt gewählt</option>
                    {#each projekte.filter(p => p.woche) as p}
                      <option value={p.id} selected={modal_s.woche}>{`${p.titel} – ${p.leitung} (${p.gewaehlt_woche}/${p.max_teilnehmer}`})</option>
                    {/each}
                    <option value={0} selected={modal_s.woche === 0}>Krank/Beurlaubt</option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="field is-horizontal">
          <div class="field-label is-normal">
            <label class="label">Mo/Di</label>
          </div>
          <div class="field-body">
            <div class="field is-narrow">
              <div class="control">
                <div class="select is-fullwidth">
                  <select bind:value={selected_mo_di} on:change={wahl_aendern}>
                    <option value={null}>Kein Projekt gewählt</option>
                    {#each projekte.filter(p => p.mo_di) as p}
                      <option value={p.id} selected={modal_s.mo_di}>{`${p.titel} – ${p.leitung} (${p.gewaehlt_mo_di}/${p.max_teilnehmer}`})</option>
                    {/each}
                    <option value={0} selected={modal_s.mo_di === 0}>Krank/Beurlaubt</option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="field is-horizontal">
          <div class="field-label is-normal">
            <label class="label">Mi/Do</label>
          </div>
          <div class="field-body">
            <div class="field is-narrow">
              <div class="control">
                <div class="select is-fullwidth">
                  <select bind:value={selected_mi_do} on:change={wahl_aendern}>
                    <option value={null}>Kein Projekt gewählt</option>
                    {#each projekte.filter(p => p.mi_do) as p}
                      <option value={p.id} selected={modal_s.mi_do}>
                        {`${p.titel} – ${p.leitung} (${p.gewaehlt_mi_do}/${p.max_teilnehmer}`})
                      </option>
                    {/each}
                    <option value={0} selected={modal_s.mi_do === 0}>Krank/Beurlaubt</option>
                  </select>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
      <footer class="modal-card-foot">
        Änderungen sind sofort wirksam
      </footer>
    </div>
  </div>
{/if}

{@debug}
<script>
  export let schueler, privat
  let projekte = [];
  let klassen = [];
  let modal = false, modal_s, selected_woche, selected_mo_di, selected_mi_do;
  function modalset (s) {
    modal = true
    modal_s=s
  }
  const { Pool } = R('pg')
  const pool = new Pool({ connectionString: privat.mein_bk_db})
  import { onMount, onDestroy } from 'svelte';
    pool.query(`SELECT id, titel, leitung, woche, mo_di, mi_do, max_teilnehmer,
                  (SELECT COUNT(*)
                    FROM wahlen
                    WHERE projekte.id = wahlen.woche
                  ) as gewaehlt_woche,
                  (SELECT COUNT(*)
                    FROM wahlen
                    WHERE projekte.id = wahlen.mo_di
                  ) as gewaehlt_mo_di,
                  (SELECT COUNT(*)
                    FROM wahlen
                    WHERE projekte.id = wahlen.mi_do
                  ) as gewaehlt_mi_do
                FROM projekte`,
      (err, resp) => projekte = resp.rows)
    pool.query(`SELECT * FROM klassen`,
      (err, resp) => klassen = resp.rows)
  function wahl (s) {
    if (s.woche === s.mo_di && s.woche === s.mi_do) return 'danger'
    else if (typeof(s.mo_di) !== typeof(s.mi_do)) return 'warning'
    else if ([s.mo_di, s.mi_do, s.woche].includes(0)) return 'info'
    else return 'success'
  }
  async function wahl_aendern () {
    const text = `INSERT INTO wahlen(schueler_hashid, woche, mo_di, mi_do)
                    VALUES($1, $2, $3, $4)
                  ON CONFLICT (schueler_hashid) DO
                    UPDATE SET woche=$2, mo_di=$3, mi_do=$4
                  RETURNING *`
    const values = [modal_s.hashid, selected_woche, selected_mo_di, selected_mi_do]
    try {
      await pool.query(text, values)
    } catch(err) {
      console.log(err.stack)
    }
  }
  let update
  async function switcher(i, id) {
    // const klasse = klassen.find(x => x.klasse === k.klasse)
    // klasse.abwesenheit = k.abwesenheit === null ?  4 : null
    klassen[i].abwesenheit = id
    klassen = klassen
    console.log(klassen)
  }
</script>
