import * as prompt from 'prompt-async';
import { v4 as uuid } from 'uuid';

import { secureHash } from './generate';
import { db } from './db';

const pr = async (message) => {
  const { test } = (await prompt.get({
    properties: {
      test: {
        message,
      },
    },
  }));

  return test;
};

export const initDB = async (init: boolean, reset: boolean): Promise<void> => {
  prompt.start();

  console.log('initialisiere Datenbank...');

  const ed = db.getDB();
  const colls = ['person','organizer','event','apparatus'];

  if (reset) {
    const test = await pr('Wirklich löschen? Bitte mit "JA!" bestätigen!');

    if (test === 'JA!') {
      console.log('setze Collections zurück...');

      await Promise.all(colls.map(c => new Promise<void>(async (resolve) => {
        if (await ed.collection(c).findOne() !== null) {
          await new Promise(resolve2 => ed.collection(c).drop(resolve2));
        }
        if (await ed.collection(`o_${c}`).findOne() !== null) {
          await new Promise(resolve2 => ed.collection(`o_${c}`).drop(resolve2));
        }
        resolve();
      })));
      console.log('   Collections geleert!');
    }
  }

  const collections: any[] = await new Promise(resolve => ed.listCollections().toArray((e, i) => resolve(i)));

  console.log('erstelle Collections...');
  colls.forEach(c => {
    if (!collections.find(C => C.name === c)) {
      ed.createCollection(c);
    }
    if (!collections.find(C => C.name === `o_${c}`)) {
      ed.createCollection(`o_${c}`);
    }
  });
  console.log('   Collections erstellt!');

  console.log('Überprüfe auf Master-Zugänge...');
  const master = await db.fetch('person', {'master': true})
  console.log(`   ${master.length} Zugänge gefunden`);

  if (init) {
    const anlegen = await pr('   Weiterer Zugang anlegen? (y/j)');
    if (['y', 'j', 'yes', 'ja'].find(t => t === anlegen.toLowerCase())) {
      const email = await pr('   neue E-Mail-Adresse eingeben');
      const passwort = await pr('   neues Passwort eingeben');
      const hash = await secureHash(passwort);

      const neu = {
        _id: uuid(),
        givenName: 'AAA_MASTER',
        familyName: 'AAA_MASTER',
        passwort: hash,
        email: email,
        master: true,
      };

      db.insert('person', neu, null).then()

      console.log('   Nutzer angelegt!');
    }
  }

  console.log('Datenbank bereit!');
}