require('dotenv').config();
const puppeteer = require('puppeteer');

const LOGIN = process.env.WEBI_LOGIN;
const PWD = process.env.WEBI_PWD;
const XIVO_IP = process.env.XIVO_IP;
const PREFIX = process.env.QUEUE_PREFIX;
const PREFIX_START_NUMBER = parseInt(process.env.QUEUE_PREFIX_START_NUMBER);
const NUMBER = parseInt(process.env.QUEUE_NUMBER);
const CONTEXT = process.env.CONTEXT;
const COUNT = process.env.QUEUE_COUNT;

(async () => {
    const argsArray = [
        '--disable-setuid-sandbox',
        '--disable-accelerated-2d-canvas',
        '--disable-dev-shm-usage',
        '--autoplay-policy=no-user-gesture-required',
        '--no-sandbox',
    ];
    const url = `https://${XIVO_IP}/callcenter/index.php/settings/queues/?act=add`;
    let browser;
    let context;
    let page;

    const init = async () => {
        browser = await puppeteer.launch({ headless: "new", ignoreHTTPSErrors: true, args: argsArray });
        context = browser.defaultBrowserContext();
        await context.overridePermissions(url, ["notifications"]);
        page = await browser.newPage();
        await page.goto(`${url}`, { waitUntil: 'networkidle2' });
    }

    const loginToWebi = async () => {
        await page.evaluate((login, pwd) => {
            document.querySelector('#it-login').value = login;
            document.querySelector('#it-password').value = pwd;
            document.querySelector('#it-submit').click();
        }, LOGIN, PWD)
        await page.waitForNavigation();
    }

    const checkForErrors = async () => {
        error = await page.$('#report-xivo-error');
        return error != null
    }

    const createErrorReport = async () => {
        console.log('We have errors...')
        const xivoErrors = await page.evaluate(() => {
            return Array.from(document.querySelectorAll('#report-xivo-error li')).map(li => li.outerText);
        })
        xivoErrors.forEach(xe => console.log(`[ERROR]: ${xe}`));
    }

    const createQueue = async (index) => {
        await page.evaluate((context, prefix, number, prefixStartNumber, index) => {
            const queueName = `${prefix}${prefixStartNumber + index}`;
            document.querySelector('#it-queuefeatures-name').value = queueName;
            document.querySelector('#it-queuefeatures-displayname').value = queueName;
            document.querySelector('#it-queuefeatures-number').value = number + index;
            document.querySelector('#it-queuefeatures-context').value = context;
            document.querySelector('#it-submit').click();
        }, CONTEXT, PREFIX, NUMBER, PREFIX_START_NUMBER, index)
        await page.waitForNavigation();
        const isError = await checkForErrors()
        if (isError) {
            await createErrorReport();
        }
        await page.goto(`${url}`, { waitUntil: 'networkidle2' });
    }

    const tearDown = async () => {
        await page.close();
        await browser.close();
    }

    await init()
    await loginToWebi();
    for (let i = 0; i < COUNT; i++) {
        console.log(`Creating queue ${i}.`)
        await createQueue(i);
    }
    await tearDown();
})()
