import puppeteer from 'puppeteer';

// args auswerten mit --path und --browser, get from args
const args = process.argv;

const config = {};


for (let i = 0; i < args.length; i++) {
    if (args[i] === '--path') {
        config.path = args[i + 1];
    }
    if (args[i] === '--browser') {
        config.browser = args[i + 1];
    }
}

if (!config.path) {
    console.error('Path is required, please provide --path');
    process.exit(1);
}

if (!config.browser) {
    console.error('Browser is required, please provide --browser');
    process.exit(1);
}


(async () => {
    const browser = await puppeteer.launch({
        headless: 'new', // if you want to see the browser, set this to false
        executablePath: config.browser,
        //args: ['--no-sandbox',"--window-size=1440,1000", "--no-sandbox", "--disable-setuid-sandbox", "--disable-gpu"],
        args: ["--disable-gpu"],
        userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36',
        waitUntil: 'load', 
        timeout: 0,
        protocolTimeout: 0,
        dumpio: true
    });

    const page = await browser.newPage();
    const fileUrl = 'file://' + config.path;

    console.log('Loading page... '+fileUrl);

    await page.goto(fileUrl, {waitUntil: 'load', timeout: 0});
    
    const title = await page.title();
    console.log('Page title:', title);

    page.on('console', async e => {
        const args = await Promise.all(e.args().map(a => a.jsonValue()));
        console[e.type() === 'warning' ? 'warn' : e.type()](...args);
    });
    


    console.log('Running tests...');
    await page.waitForFunction('document.getElementById("mocha-done").textContent.length > 0', 
        { 
            timeout: 1000000,
            polling: 1000
            
            
        }
    ) ;

    const passes = await page.evaluate(() => document.getElementById('mocha-stats').querySelector('li.passes').textContent);
    const failures = await page.evaluate(() => document.getElementById('mocha-stats').querySelector('li.failures').textContent);
    const duration = await page.evaluate(() => document.getElementById('mocha-stats').querySelector('li.duration').textContent);
    
    const error = await page.evaluate(() => document.getElementById('mocha-errors').textContent);

    console.log('Tests passed:', passes);
    console.log('Tests failed:', failures);
    console.log('Duration:', duration);
    
    if (error.length > 0) {
        console.error('Tests failed: ', error);
    } else {
        console.log('Tests passed');
    }

    await browser.close();
})();