require('@babel/register')({presets: ['@babel/env']});
require('core-js/stable');
require('regenerator-runtime/runtime');
require('vn-loopback/server/boot/date')();

const axios = require('axios');
const Docker = require('../../db/docker.js');
const e2eConfig = require('./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() {
    if (process.argv[2] === 'show')
        process.env.E2E_SHOW = true;

    const container = new Docker('salix-db');

    await container.run();

    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,
    });

    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();