import {expect, test} from '@jest/globals';
import {__runLogin} from './login.test';
import {jestState} from '../form.spec';

/**
 * Get expected data for nav bar.
 * @return {[object]}
 */
function getNavBarExpectedData() {
    const chunk = jestState.envData.root + '/wp-admin/options-general.php?page=spbc&spbc_tab=';
    const tabOwnClassChunk = '.spbc_tab_nav-';
    const navBarTabs = [
        'critical_updates',
        'traffic_control',
        'fswatcher',
        'scanner',
        'backups',
        'security_log',
        'settings_general',
        'summary',
    ];
    let data = [];
    for (const navBarTab of navBarTabs) {
        data.push({tab: navBarTab, tabOwnClass: tabOwnClassChunk + navBarTab, link: chunk + navBarTab});
    }
    return data;
}

export async function __navBarTabsExist() {
    // run settings tests there
    const navBarLinks = getNavBarExpectedData();

    await jestState.page.goto(
        jestState.envData.root + '/wp-admin/options-general.php?page=spbc&spbc_tab=settings_general',
        {waitUntil: 'load'},
    );
    await jestState.page.waitForSelector('.spbc_tabs_nav_wrapper');
    for (let i = 0; i < navBarLinks.length; i++) {
        await jestState.page.$eval(navBarLinks[i].tabOwnClass, (el) => el.innerText);
    }
}

export async function __navBarTabIsActiveOnClick() {
    // run settings tests there
    const navBarLinks = getNavBarExpectedData();

    for (const navBarLink of navBarLinks) {
        await jestState.page.goto(navBarLink.link, {waitUntil: 'load'});
        await jestState.page.waitForSelector('.spbc_tabs_nav_wrapper');
        const navTabClassList = await jestState.page.$eval(navBarLink.tabOwnClass, (el) => el.className);
        expect(navTabClassList).toContain('spbc_tab_nav--active');
    }
}

/**
 * Run navigation bar tests.
 * This test is a wrapper for group of tests.
 * @param {boolean} doLogin
 * @return {void}
 */
export function groupNavBar(doLogin = true) {
    if (doLogin) {
        test('LOGIN', async () => {
            await __runLogin();
        }, jestState.globals.globalTimeout);
    }
    test('NAV BAR EXIST', async () => {
        await __navBarTabsExist();
    }, jestState.globals.globalTimeout);
    test('NAV BAR TAB ACTIVE ON CLICK', async () => {
        await __navBarTabIsActiveOnClick();
    }, jestState.globals.globalTimeout);
    // more test there
}
