import {ConfigHelper} from "../../common-helpers/config-helper";
import logger from "../../reporting-helpers/logger";
import {PageConfigTypes} from "../../../custom-types/pageConfig-types";
import {CustomExpect} from "../../common-helpers/custom-expect";
import {browser, $, $$, expect} from '@wdio/globals'

/**
 * Check if element by index exists.
 * The function should be used if we are expecting to find multi element occurrence
 * Element index in Array starts from [0], but the end user on UI will see 1st, 2nd, 3rd, 4th... element
 * @param  {number}   elementPosition  Passed to the function should be >= 1
 *                                   index - will be calculated and adjusted accordingly
 * @param  {String}   pageObject     Element selector
 * @param  {boolean}   falseCase     Whether to check if element by Index should exist or not
 */


export default async (elementPosition: number = 0, pageConfig: PageConfigTypes, falseCase: boolean) => {
    const index = elementPosition - 1;
    let elementsByIndex = await $$(pageConfig.selector)[index]
    if ((elementsByIndex == undefined) && (!falseCase)) {
        throw Error(`No ${pageConfig.elementKey} element found at ${index + 1} position. Check that you passing correct element position or use another step definition that calls checkIfElementExists.ts instead`);
    }
    if ((elementsByIndex == undefined) && (falseCase)) {
        throw Error(`NO ${pageConfig.elementKey} element found at ${index + 1} position. Check that you passing correct element position or use another step definition that calls checkIfElementExists.ts instead`);
    } else if (falseCase) {
        CustomExpect.expectToEqual(await elementsByIndex.isDisplayed(), false, `Element "${pageConfig.pageId}.${pageConfig.elementKey}" exists at position "${elementPosition}"`)
        logger.info(`The ${pageConfig.elementKey} element is NOT present at ${elementPosition} position`);
    } else {
        CustomExpect.expectToEqual(await elementsByIndex.isDisplayed(), true, `Element "${pageConfig.pageId}.${pageConfig.elementKey}" does not exist at position "${elementPosition}"`)
    }
};

