<section class="section no-print">
  <div class="container no-print">
    <h1 class="title">Mein BK</h1>
    <div>
      <span class="tag is-success" on:click={()=>hole_lokale_schueler()} style="cursor: pointer;">
        {schueler_lokal.length} Schüler in der Datenbank
      </span>
    </div>
    <br>
    <div class="field">
      <div class="control">
        <input class="input" type="text" placeholder="Filter" bind:value={suche}>
      </div>
    </div>
  </div>
  <div class="container no-print">
    <div class="tabs">
      <ul>
        <li class:is-active={active === Vouchers} on:click={() => active=Vouchers}>WLAN</li>
        <li class:is-active={active === ProjektwocheSchueler} on:click={() => active=ProjektwocheSchueler}>PW Schüler</li>
        <li class:is-active={active === ProjektwocheLehrer} on:click={() => active=ProjektwocheLehrer}>PW Projekte</li>
        <li class:is-active={active === ProjektwocheDrucksache} on:click={() => active=ProjektwocheDrucksache}>PW Drucksache</li>
        <li class:is-active={active === ProjektwocheTnListen} on:click={() => active=ProjektwocheTnListen}>PW Teilnehmerliste</li>
        <li class:is-active={active === SVWahl} on:click={() => active=SVWahl}>SV-Wahl</li>
        <li class:is-active={active === Einstellungen} on:click={() => active=Einstellungen}>Einstellungen</li>
        <li class:is-active={active === Infos} on:click={() => active=Infos}>Infos</li>
        <li class:is-active={active === Teams} on:click={() => active=Teams}>Teams</li>
        <li class:is-active={active === Reservierung} on:click={() => active=Reservierung}>iPads</li>
      </ul>
    </div>
    <svelte:component this={active} schueler={schueler_filter} {privat} {einstellungen} {knexConfig}/>
  </div>
</section>
<!-- <div class="container">
</div> -->

<style>
  @import 'node_modules/bulma/css/bulma.css';
  .tabs li.is-active {
    border-bottom-color: #3273dc;
    color: #3273dc;
  }
  .tabs li:hover {
    border-bottom-color: #3273dc;
  }
  .tabs li {
    align-items: center;
    border-bottom-color: #dbdbdb;
    border-bottom-style: solid;
    border-bottom-width: 1px;
    color: #4a4a4a;
    display: flex;
    justify-content: center;
    margin-bottom: -1px;
    padding: 0.5em 1em;
    vertical-align: top;
    cursor: pointer;
    text-decoration: none;
  }
</style>

<script>
  import Vouchers from './components/vouchers.svelte'
  import ProjektwocheSchueler from './components/projektwoche-schueler.svelte'
  import ProjektwocheLehrer from './components/projektwoche-lehrer.svelte'
  import ProjektwocheDrucksache from './components/projektwoche-drucksache.svelte'
  import ProjektwocheTnListen from './components/projektwoche-tn-listen.svelte'
  import SVWahl from './components/svwahl.svelte'
  import Einstellungen from './components/einstellungen.svelte'
  import Infos from './components/infos.svelte'
  import Teams from './components/teams.svelte'
  import Reservierung from './components/reservierung.svelte'
  export let knexConfig, privat
  let active = Teams
  let suche = ''

  const { Pool } = R('pg')
  const mysql = R('mysql')
  let schueler_entfernt = [], schueler_lokal = []
  let einstellungen = {}
  const postgres = new Pool({ connectionString: privat.mein_bk_db})
  postgres.query(`SELECT * FROM einstellungen`)
    .then(res => {
      einstellungen = res.rows[0]
      einstellungen || postgres.query(`INSERT INTO einstellungen DEFAULT VALUES RETURNING *`)
        .then(res => einstellungen = res.rows[0])
    })
  postgres.query(`SELECT schueler.*, AGE(schueler.geburtsdatum) as alter,
                    wlan.voucher,
                    wahlen.*
              FROM schueler
              LEFT JOIN wlan ON schueler.id = wlan.schueler_id
              LEFT JOIN wahlen ON schueler.id = wahlen.schueler_id`)
        .then(resp => {
          schueler_entfernt = resp.rows
        })
  const mysql_connection = mysql.createConnection(knexConfig.connection)
  mysql_connection.connect()
  function hole_lokale_schueler () {
    mysql_connection.query(`SELECT ID AS id, Name, Vorname, Klasse, Volljaehrig, TIMESTAMPDIFF(YEAR, Geburtsdatum, CURDATE()) AS age,
                              CONCAT (LOWER (Vorname), ' ', LOWER (Name)) AS vollname
                            FROM schueler
                            WHERE Status = 2 AND Geloescht = "-" AND Gesperrt = "-"
                            ORDER BY Klasse, Name ASC`,
      (e, res) => {
        schueler_lokal = res
      })
  }
const groupBy = (arr, id) => arr.reduce(
  (entryMap, f) => {
    const fx = id.split('.').reduce((p,c)=>p&&p[c]||null, f)
    return entryMap.set(fx, [...entryMap.get(fx)||[], f])
  },
  new Map()
)
  hole_lokale_schueler()
  $: merged = schueler_lokal.map(itm => ({
      ...schueler_entfernt.find((item) => (item.id === itm.id) && item),
      ...itm}))
  $: schueler_filter = Object.fromEntries(groupBy(merged.filter(s => s.vollname.includes(suche.toLowerCase())), 'Klasse'))
</script>
