import puppeteer from 'puppeteer';
import {unlinkSync} from 'fs';
import {existsSync} from 'fs';
import {mkdtempSync, rmSync} from 'fs';
import {tmpdir} from 'os';
import path from 'path';


// 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 userDataDir = mkdtempSync(path.join(tmpdir(), 'monster-webtest-'));
    let browser;

    try {
        try {
            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",
                    '--no-sandbox',
                    '--disable-setuid-sandbox',
                    `--user-data-dir=${userDataDir}`,
                    '--enable-logging=stderr',
                    '--disable-web-security',
                    '--disable-features=IsolateOrigins',
                    '--disable-site-isolation-trials',
                    '--disable-crash-reporter',
                    '--disable-breakpad',
                    '--no-first-run',
                    '--no-default-browser-check',
                    '--disable-dev-shm-usage'
                ],
                
                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
            });
        } catch (error) {
            console.error('Browser launch failed');
            console.error(`Browser executable: ${config.browser}`);
            console.error(`Browser profile: ${userDataDir}`);
            throw error;
        }

        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 em').textContent);
        const failures = await page.evaluate(() => document.getElementById('mocha-stats').querySelector('li.failures em').textContent);
        const duration = await page.evaluate(() => document.getElementById('mocha-stats').querySelector('li.duration em').textContent);
        
        console.log('Tests passed:', passes);
        console.log('Tests failed:', failures);
        console.log('Duration:', duration);
        
        if (existsSync('screenshot.png')) {
            unlinkSync('screenshot.png');
        }
        
        await page.screenshot({ path: 'screenshot.png' });

        const failuresAsInt = parseInt(failures);
        if (failuresAsInt > 0) {
            console.error('Tests failed');

            await page.evaluate(() => {
                document.querySelectorAll('.test.fail').forEach((node) => {
                    console.error(node.textContent);
                });
            });

            process.exitCode = 1;
        } else {
            console.log('Tests passed');
        }
    } finally {
        if (browser) {
            await browser.close().catch(() => {});
        }

        rmSync(userDataDir, { recursive: true, force: true });
    }

})();
