/*
 * Copyright (C) Sapphirecode - All Rights Reserved
 * This file is part of Auth-Server-Helper which is released under MIT.
 * See file 'LICENSE' for full license details.
 * Created by Timo Hocker <timo@scode.ovh>, January 2021
 */

/* eslint-disable no-console */
import http from 'http';
import ks from '../lib/KeyStore';

export class Response extends http.IncomingMessage {
  body?: string;
}

export function get (
  // eslint-disable-next-line default-param-last
  headers: http.OutgoingHttpHeaders = {},
  body?: string
): Promise<Response> {
  return new Promise ((resolve) => {
    const req = http.request ('http://localhost:3000', {
      headers,
      method: typeof body === 'string' ? 'POST' : 'GET'
    }, (res: Response) => {
      let data = '';
      res.on ('data', (d) => {
        data += d;
      });
      res.on ('end', () => {
        res.body = data;
        resolve (res);
      });
    });
    if (typeof body === 'string')
      req.write (body);
    req.end ();
  });
}

export function modify_signature (signature: string): string {
  const dec = signature.split ('.');
  dec[1] = '';
  return dec.join ('.');
}

/* eslint-disable dot-notation */
export function assert_keystore_state (): void {
  const set = ks['_keys'];
  const keys = Object.keys (set);
  if (keys.length !== 0) {
    const has_sign = keys.filter (
      (v) => typeof set[v].private_key !== 'undefined'
    ).length;
    console.warn ('keystore gc not running!');
    console.warn (`${keys.length} keys with ${has_sign} signature keys left`);
    ks['_keys'] = {};
  }
}
/* eslint-enable dot-notation */

export function clock_setup ():void {
  assert_keystore_state ();

  const date = (new Date);
  date.setHours (0, 0, 2, 0);
  jasmine.clock ()
    .install ();
  jasmine.clock ()
    .mockDate (date);
}

export function clock_finalize ():void {
  jasmine.clock ()
    .tick (30 * 24 * 60 * 60 * 1000);
  // eslint-disable-next-line dot-notation
  ks['garbage_collect'] ();
  jasmine.clock ()
    .uninstall ();
}