/* eslint-disable no-console */
require('@babel/register')({presets: ['@babel/env']});
require('core-js/stable');
require('regenerator-runtime/runtime');
require('vn-loopback/server/boot/date')();
const getopts = require('getopts');

const path = require('path');
const Myt = require('@verdnatura/myt/myt');
const Run = require('@verdnatura/myt/myt-run');

const axios = require('axios');
const e2eConfig = require('./helpers/config.js');
const log = require('fancy-log');

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

async function test() {
    const opts = getopts(process.argv.slice(2), {
        boolean: ['show']
    });
    if (opts.show)
        process.env.E2E_SHOW = true;

    console.log('Building and running DB container.');
    const myt = new Myt();
    await myt.init({workspace: path.join(__dirname, '..')});
    await myt.run(Run);
    await myt.deinit();

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

    const specFiles = [
        `./e2e/paths/01*/*[sS]pec.js`,
        `./e2e/paths/02*/*[sS]pec.js`,
        `./e2e/paths/03*/*[sS]pec.js`,
        `./e2e/paths/04*/*[sS]pec.js`,
        `./e2e/paths/05*/*[sS]pec.js`,
        `./e2e/paths/06*/*[sS]pec.js`,
        `./e2e/paths/07*/*[sS]pec.js`,
        `./e2e/paths/08*/*[sS]pec.js`,
        `./e2e/paths/09*/*[sS]pec.js`,
        `./e2e/paths/10*/*[sS]pec.js`,
        `./e2e/paths/11*/*[sS]pec.js`,
        `./e2e/paths/12*/*[sS]pec.js`,
        `./e2e/paths/13*/*[sS]pec.js`,
        `./e2e/paths/**/*[sS]pec.js`
    ];

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

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

    await backendStatus();

    jasmine.jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
    await jasmine.execute();
}

async function backendStatus() {
    log('Awaiting backend connection.');

    const milliseconds = 1000;
    const maxAttempts = 10;

    return new Promise(resolve => {
        let timer;
        let attempts = 1;
        timer = setInterval(async() => {
            try {
                attempts++;
                const url = `${e2eConfig.url}/api/Applications/status`;
                const {data} = await axios.get(url);

                if (data == true) {
                    clearInterval(timer);
                    log('Backend connection stablished!');
                    resolve(attempts);
                }
            } catch (error) {
                if (error && attempts >= maxAttempts) {
                    log('Could not connect to backend');
                    process.exit();
                }
            }
        }, milliseconds);
    });
}

test();