/* eslint-disable no-console */
const path = require('path');
const Myt = require('@verdnatura/myt/myt');
const Run = require('@verdnatura/myt/myt-run');
let dataSources = require('../loopback/server/datasources.json');

let server;

process.on('warning', warning => {
    console.log(warning.name);
    console.log(warning.message);
    console.log(warning.stack);
});

process.on('SIGUSR2', rmServer);
process.on('exit', rmServer);

async function rmServer() {
    if (!server) return;
    await server.rm();
    server = null;
}

async function test() {
    console.log('Building and running DB container.');

    const isCI = process.argv[2] === 'ci';

    const myt = new Myt();
    await myt.init({
        workspace: path.join(__dirname, '..'),
        random: true,
        ci: isCI,
        tmpfs: process.platform == 'linux',
        network: isCI ? 'jenkins' : null
    });
    server = await myt.run(Run);
    await myt.deinit();
    const {dbConfig} = server;

    console.log('Initializing backend.');

    dataSources = JSON.parse(JSON.stringify(dataSources));
    Object.assign(dataSources.vn, {
        host: dbConfig.host,
        port: dbConfig.port
    });

    const bootOptions = {dataSources};
    const app = require('vn-loopback/server/server');
    await new Promise((resolve, reject) => {
        app.boot(bootOptions,
            err => err ? reject(err) : resolve());
    });
    // FIXME: Workaround to wait for loopback to be ready
    await app.models.Application.status();

    console.log('Running tests.');

    const Jasmine = require('jasmine');
    const jasmine = new Jasmine();

    const SpecReporter = require('jasmine-spec-reporter').SpecReporter;
    jasmine.addReporter(new SpecReporter({
        spec: {
            displaySuccessful: isCI,
            displayPending: isCI
        },
        summary: {
            displayPending: false,
        }
    }));

    if (isCI) {
        const JunitReporter = require('jasmine-reporters');
        jasmine.addReporter(new JunitReporter.JUnitXmlReporter());

        jasmine.exitOnCompletion = true;
        jasmine.jasmine.DEFAULT_TIMEOUT_INTERVAL = 900000;
    }

    const backSpecs = [
        './back/**/*[sS]pec.js',
        './loopback/**/*[sS]pec.js',
        './modules/*/back/**/*.[sS]pec.js'
    ];

    jasmine.loadConfig({
        spec_dir: '.',
        spec_files: backSpecs,
        helpers: [],
    });

    await jasmine.execute();

    console.log('Stopping.');

    if (app) await app.disconnect();
    await rmServer();

    console.log('Tests ended.\n');
}

test();