/*******************************
NE PAS MODIFIER, FICHIER GENERE
*******************************/

/**
 * Software Name : UUV
 *
 * SPDX-License-Identifier: MIT
 *
 * This software is distributed under the MIT License,
 * see the "LICENSE" file for more details
 *
 * Authors: NJAKO MOLOM Louis Fredice & SERVICAL Stanley
 * Software description: Make test writing fast, understandable by any human
 * understanding English or French.
 */

import { DataTable, Given, Then, When } from "@badeball/cypress-cucumber-preprocessor";
import { Context } from "../_context";
import "../../../../cypress/commands";
import { Method } from "cypress/types/net-stubbing";

import {
    assertTextContent,
    click,
    findWithRoleAndName,
    findWithRoleAndNameAndContent,
    findWithRoleAndNameAndContentDisable,
    findWithRoleAndNameAndContentEnable,
    findWithRoleAndNameFocused,
    notFoundWithRoleAndName,
    withinRoleAndName
} from "../core-engine";
import { A11yReferenceEnum } from "@uuv/a11y";
import { expectTableToHaveContent, pressKey, removeHeaderSeparatorLine } from "./../_.common";

/**
 * Navigate to the Uri passed as a argument (full url consisting of the BASE_URL + Uri) or navigate to Url if begin with http:// or https://
 * */
When(`I visit path {string}`, function(siteUrl: string) {
  if (siteUrl.match("^http:\\/\\/|https:\\/\\/")) {
    cy.visit(`${siteUrl}`);
  } else {
    cy.visit(`${Cypress.config().baseUrl}${siteUrl}`);
  }
});

/**
 * Triggers a click on the selected element.<br/>Make sure you've selected an element beforehand with the <strong>within...</strong> phrases.
 * */
When(`I click`, function() {
    if (haveKeyBoardFocused()) {
        cy.focused().click();
    } else {
        cy.uuvCheckContextWithinFocusedElement().then(context => {
            context.withinFocusedElement!.click();
        });
    }
});

/**
 * Triggers a click on the element with given role and specific name
 * */
When(`I click on element with role {string} and name {string}`, function(role: string, name: string) {
  click(role, name);
});

/**
 * Writes the sentence passed as a parameter (useful for example to fill in a form field).<br/>Make sure you've selected an element beforehand with the <strong>within...</strong> phrases.
 * */
When(`I type the sentence {string}`, function(textToType: string) {
    type(textToType);
});

/**
 * Writes the sentence passed as a parameter (useful for example to fill in a form field).<br/>Make sure you've selected an element beforehand with the <strong>within...</strong> phrases.
 * */
When(`I enter the value {string}`, function(textToType: string) {
    type(textToType);
});

/**
 * Press specified key multiple times using | as: num|{key}
 * */
When(`I press {int} times on {string}`, function(nbTimes: number, key: string) {
  for (let i = 1; i <= nbTimes; i++) {
    pressKey(key);
  }
});

/**
 * Press specified key: <table><thead><tr><th>Key</th><th>Description</th></tr></thead><tbody><tr><td>{tab}</td><td>Tabulation</td></tr><tr><td>{reverseTab}</td><td>Reverse tabulation</td></tr><tr><td>{down}</td><td>Arrow Down</td></tr><tr><td>{right}</td><td>Arrow Right</td></tr><tr><td>{left}</td><td>Arrow Left</td></tr><tr><td>{up}</td><td>Arrow Up</td></tr></tbody></table><br/>Make sure you've selected an element beforehand with the <strong>within...</strong> phrases.
 * */
When(`I press {string}`, function(key: string) {
  pressKey(key);
});

/**
 * Move to the previous html element that can be reached with back Tab<br/><a target='_blank' href='https://github.com/e2e-test-quest/uuv/blob/main/example/en-keyboard.feature'>Examples</a>
 * */
When(`I go to previous keyboard element`, function() {
  pressKey("{reverseTab}");
});

/**
 * Move to the next html element that can be reached with Tab<br/><a target='_blank' href='https://github.com/e2e-test-quest/uuv/blob/main/example/en-keyboard.feature'>Examples</a>
 * */
When(`I go to next keyboard element`, function() {
  pressKey("{tab}");
});

////////////////////////////////////////////
// Context ACTIONS
////////////////////////////////////////////

/**
 * Sets the viewport dimensions with one of the presets defined by your runtime engine as Cypress: [Link](https://docs.cypress.io/api/commands/viewport#Arguments) or Playwright: [Link](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/server/deviceDescriptorsSource.json)
 * */
Given(`I set viewport to preset {string}`, function(viewportPreset: string) {
  cy.viewport(viewportPreset as Cypress.ViewportPreset);
});

/**
 * Sets the viewport dimensions to the specified width and length
 * */
Given(
 `I set viewport with width {int} and height {int}`,
 function(width: number, height: number) {
   cy.viewport(width, height);
 }
);

/**
 * Start a keyboard navigation session from the top of the page<br/><a target='_blank' href='https://github.com/e2e-test-quest/uuv/blob/main/example/en-keyboard.feature'>Examples</a>
 * */
Given(
 `I start a keyboard navigation from the top of the page`,
 function() {
     cy.get("body").last().realClick({ x: 0.5, y: 0.5 });
 }
);

/**
 * Sets the timeout value (in millisecond) for finding element in the DOM <br />⚠ remember to deselect the element with <b>[I reset context](#i-reset-context)</b> if you're no longer acting on it
 * */
When(`I set timeout with value {int}`, function(newTimeout: number) {
  cy.uuvPatchContext({
    timeout: newTimeout
  });
});

/**
 * key.when.withinElement.description
 * */
When(`within the element with role {string} and name {string}`, function(role: string, name: string) {
  withinRoleAndName(role, name);
});

/**
 * Selects the element whose aria-label is specified <br />⚠ remember to deselect the element with <b>[I reset context](#i-reset-context)</b> if you're no longer acting on it
 * */
When(`within the element with aria-label {string}`, function(expectedAriaLabel: string) {
  const foundedElement = cy.uuvFindByLabelText(expectedAriaLabel, {})
   .uuvFoundedElement()
   .should("exist");

  cy.uuvPatchContext({
    withinFocusedElement: foundedElement
  });
});

/**
 * key.when.withinElement.description
 * */
When(`within the element with testId {string}`, function(testId: string) {
  const foundedElement = cy.uuvFindByTestId(testId)
   .uuvFoundedElement()
   .should("exist");

  cy.uuvPatchContext({
    withinFocusedElement: foundedElement
  });
});

/**
 * Selects the element whose selector is specified <br />⚠ remember to deselect the element with <b>[I reset context](#i-reset-context)</b> if you're no longer acting on it
 * */
When(`within the element with selector {string}`, function(selector: string) {
  const foundedElement = cy.uuvGetContext().then(context => {
    const parentElement = context.withinFocusedElement;
    if (parentElement) {
      // console.log("parentElement: ", parentElement);
      return parentElement.should("exist").within(() => {
        cy.get(selector).as("foundedChildElement");
      });
    }
    cy.wrap(null).as("foundedChildElement");
    return cy.get(selector);
  }).uuvFoundedElement()
   .should("exist");

  cy.uuvPatchContext({
    withinFocusedElement: foundedElement
  });
});

/**
 * Deletes selected element and timeout
 * */
When(`I reset context`, function() {
    cy.wrap(new Context()).as("context");
    if (haveKeyBoardFocused()) {
        cy.focused().blur();
    } else {
        cy.window().trigger("blur");
    }
});

/**
 * Mock a named API response with body. <i>If you use Playwright as runtime engine, <b>request</b> and <b>named</b> are unused.</i>
 * */
When(
 `I mock a request {} on url {string} named {string} with content {}`,
 function(verb: Method, uri: string, name: string, body: any) {
   cy
    .intercept(verb, uri, {
      body: body
    })
    .as(name);
 }
);

/**
 * Mock a named API response with status code
 * */
When(
 `I mock a request {} on url {string} named {string} with status code {int}`,
 function(verb: Method, uri: string, name: string, statusCode: number) {
   cy
    .intercept(verb, uri, {
      statusCode: statusCode
    })
    .as(name);
 }
);

/**
 * Mock a named API response with file's extension .json, .js, .coffee, .html, .txt, .csv, .png, .jpg, .jpeg, .gif, .tif, .tiff, .zip
 * */
When(
 `I mock a request {} on url {string} named {string} with fixture {}`,
 function(verb: Method, uri: string, name: string, fixture: any) {
   cy
    .intercept(verb, uri, {
      fixture: fixture
    })
    .as(name);
 }
);

////////////////////////////////////////////
// INTERCEPTION
////////////////////////////////////////////
/**
 * Sets one or more headers to the indicated http request and only for the Http method (GET / POST / etc...) passed as a argument.<i> If you use Playwright as execution engine, <b>method</b> isn't used.</i>
 * */
When(
 `I set header(s) for uri {string} and method {string}`,
 function(url: string, method: string, headersToSet: DataTable) {
   cy.intercept(method as Method, url, (req) => {
     req.headers = {
       ...req.headers,
       ...headersToSet.rowsHash()
     };
     req.continue();
   });
 }
);

/**
 * Sets one or more headers to the indicated http request
 * */
When(`I set header(s) for uri {string}`, function(url: string, headersToSet: DataTable) {
  cy.intercept(url, (req) => {
    req.headers = {
      ...req.headers,
      ...headersToSet.rowsHash()
    };
    req.continue();
  });
});

////////////////////////////////////////////
// VALIDATION
////////////////////////////////////////////

/**
 * Checks the current html page have the specified title
 * */
Then(`I should see the page title {string}`, function(pageTitle: string) {
    cy.title().should("eq", pageTitle);
});

/**
 * Checks that an Html element exists with the specified content
 * */
Then(`I should see an element with content {string}`, function(textContent: string) {
  cy.uuvFindByText(textContent, {})
   .uuvFoundedElement()
   .should("exist");
});

/**
 * Checks that an Html element does not exists with the specified content
 * */
Then(`I should not see an element with content {string}`, function(textContent: string) {
  cy.uuvFindByText(textContent, {})
   .should("not.exist");
});

/**
 * Checks that an Html element exists with the specified data-testid attribute
 * */
Then(`I should see an element with testId {string}`, function(testId: string) {
  cy.uuvFindByTestId(testId)
   .uuvFoundedElement()
   .should("exist");
});

/**
 * Checks that an Html element does not exists with the specified data-testid attribute
 * */
Then(`I should not see an element with testId {string}`, function(testId: string) {
  cy.uuvFindByTestId(testId)
   .should("not.exist");
});

/**
 * Checks that an Html element exists with the specified [accessible role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles#aria_role_types) and [name](https://russmaxdesign.github.io/html-elements-names/)
 * */
Then(`I should see an element with role {string} and name {string}`, function(role: string, name: string) {
  findWithRoleAndName(role, name);
});

/**
 * Checks that an Html element does not exists with the specified [accessible role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles#aria_role_types) and [name](https://russmaxdesign.github.io/html-elements-names/)
 * */
Then(
 `I should not see an element with role {string} and name {string}`,
  function(role: string, name: string) {
   notFoundWithRoleAndName(role, name);
 }
);

/**
 * Checks that an Html element exists with the specified [accessible role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles#aria_role_types), [name](https://russmaxdesign.github.io/html-elements-names/) and content
 * */
Then(
 `I should see an element with role {string} and name {string} and content {string}`,
  function(expectedRole: string, name: string, expectedTextContent: string) {
   findWithRoleAndNameAndContent(expectedRole, name, expectedTextContent);
 }
);

/**
 * Checks that the Html element with the specified [accessible role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles#aria_role_types) and [name](https://russmaxdesign.github.io/html-elements-names/) is focused<br/><a target='_blank' href='https://github.com/e2e-test-quest/uuv/blob/main/example/en-keyboard.feature'>Examples</a>
 * */
Then(
 `the element with role {string} and name {string} should be keyboard focused`,
  function(expectedRole: string, name: string) {
    findWithRoleAndNameFocused(expectedRole, name);
 }
);

/**
 * Checks that the Html element with the specified selector is focused<br/><a target='_blank' href='https://github.com/e2e-test-quest/uuv/blob/main/example/en-keyboard.feature'>Examples</a>
 * */
Then(
 `the element with selector {string} should be keyboard focused`,
 function(selector: string) {
   cy.get(selector).then(foundElement => {
     cy.focused().then(focusedElement => {
       expect(foundElement?.get(0)).eq(focusedElement?.get(0));
     });
   });
 }
);

/**
 * Checks that an Html element exists with the specified [accessible role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles#aria_role_types), [name](https://russmaxdesign.github.io/html-elements-names/) and content, and with the disabled attribute set to true
 * */
Then(
 `I should see an element with role {string} and name {string} and content {string} disabled`,
  function(expectedRole: string, name: string, expectedTextContent: string) {
   findWithRoleAndNameAndContentDisable(expectedRole, name, expectedTextContent);
 }
);

/**
 * Checks that an Html element exists with the specified [accessible role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles#aria_role_types), [name](https://russmaxdesign.github.io/html-elements-names/) and content, and with the disabled attribute set to false
 * */
Then(
 `I should see an element with role {string} and name {string} and content {string} not disabled`,
  function(expectedRole: string, name: string, expectedTextContent: string) {
   findWithRoleAndNameAndContentEnable(expectedRole, name, expectedTextContent);
 }
);

/**
 * Checks that an Html element exists with the specified aria-label attribute
 * */
Then(`I should see an element with aria-label {string}`, function(expectedAriaLabel: string) {
  cy.uuvFindByLabelText(expectedAriaLabel, {})
   .uuvFoundedElement()
   .should("exist");
});

/**
 * Checks that an Html element does not exists with the specified aria-label attribute
 * */
Then(`I should not see an element with aria-label {string}`, function(expectedAriaLabel: string) {
  cy.uuvFindByLabelText(expectedAriaLabel, {})
    .should("not.exist");
});

/**
 * Checks that an Html element exists with the specified aria-label attribute and content
 * */
Then(
 `I should see an element with aria-label {string} and content {string}`,
  function(expectedAriaLabel: string, expectedTextContent: string) {
   cy.uuvFindByLabelText(expectedAriaLabel, {})
    .uuvFoundedElement()
    .should("exist")
    .then((response) => {
      assert.equal(response.length, 1);
      assertTextContent(response, expectedTextContent);
    });
 }
);

/**
 * Move to the previous html element that can be reached with Tab and checks that the Html element with the specified [accessible role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles#aria_role_types) and [name](https://russmaxdesign.github.io/html-elements-names/) is focused<br/><a target='_blank' href='https://github.com/e2e-test-quest/uuv/blob/main/example/en-keyboard.feature'>Examples</a>
 * */
When(`the previous keyboard element focused should have name {string} and role {string}`, function(expectedRole: string, name: string) {
    pressKey("{reverseTab}");
    findWithRoleAndNameFocused(expectedRole, name);
});

/**
 * "Move to the next html element that can be reached with Tab and checks that the Html element with the specified [accessible role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles#aria_role_types) and [name](https://russmaxdesign.github.io/html-elements-names/) is focused<br/><a target='_blank' href='https://github.com/e2e-test-quest/uuv/blob/main/example/en-keyboard.feature'>Examples</a>
 * */
When(`the next keyboard element focused should have name {string} and role {string}`, function(expectedRole: string, name: string) {
    pressKey("{tab}");
    findWithRoleAndNameFocused(expectedRole, name);
});

/**
 * Wait that a named mock has been consumed until timeout
 * */
Then(`I should consume a mock named {string}`, function(name: string) {
  cy.wait([`@${name}`]);
});

/**
 * key.when.click.withContext.description
 * */
Then(`I wait {int} ms`, function(ms: number) {
  cy.wait(ms);
});

/**
 * Checks that there is a list with the specified [name](https://russmaxdesign.github.io/html-elements-names/) containing list items.<br/> <u>Example</u>\n```gherkin\nThen I should see a list named "test-list" and containing\n| First element   |\n| Second element  |\n| Third element   |\n```
 * */
Then(
 `I should see a list named {string} and containing`,
  function(expectedListName: string, expectedElementsOfList: DataTable) {
   cy.uuvFindByRole("list", { name: expectedListName })
    .uuvFoundedElement()
    .should("exist")
    .within(() => {
      return cy.findAllByRole("listitem", {}).then((listitem) => {
        const foundedElement: any[] = [];
        for (let i = 0; i < listitem.length; i++) {
          foundedElement.push([listitem[i].textContent]);
        }
        assert.equal(listitem.length, expectedElementsOfList.raw().length);
        assert.deepEqual(
         foundedElement,
         expectedElementsOfList.raw(),
         `expected [${foundedElement}] to be [${expectedElementsOfList.raw()}]`
        );
      });
    });
 }
);

/**
 * Checks that there is a grid with the specified [name](https://russmaxdesign.github.io/html-elements-names/) containing list items.<br/> <u>Example</u>\n```gherkin\nWhen I visit path "https://e2e-test-quest.github.io/simple-webapp/grid.html"\nThen I should see a grid named "HTML Grid Example" and containing\n| Make         | Model   | Price  |\n| ------------ | ------- | ------ |\n| Toyota       | Celica  | 35000  |\n| Ford         | Mondeo  | 32000  |\n| Porsche      | Boxster | 72000  |\n| BMW          | M50     | 60000  |\n| Aston Martin | DBX     | 190000 |\n```
 * */
Then(
    `I should see a grid named {string} and containing`,
    function(expectedListName: string, pExpectedElementsOfList: DataTable) {
        const expectedElementsOfList = removeHeaderSeparatorLine(pExpectedElementsOfList);
        cy.uuvFindByRole("grid", { name: expectedListName })
            .uuvFoundedElement()
            .should("exist")
            .within(() => {
                expectTableToHaveContent(expectedElementsOfList, "gridcell");
            });
    }
);

/**
 * Checks that there is a treegrid with the specified [name](https://russmaxdesign.github.io/html-elements-names/) containing list items.<br/> <u>Example</u>\n```gherkin\nWhen I visit path "https://e2e-test-quest.github.io/simple-webapp/treegrid.html"\nThen I should see a treegrid named "HTML Treegrid Example" and containing\n| Make         | Model   | Price  |\n| ------------ | ------- | ------ |\n| Toyota       | Celica  | 35000  |\n| Ford         | Mondeo  | 32000  |\n| Porsche      | Boxster | 72000  |\n| BMW          | M50     | 60000  |\n| Aston Martin | DBX     | 190000 |\n```
 * */
Then(
    `I should see a treegrid named {string} and containing`,
    function(expectedListName: string, pExpectedElementsOfList: DataTable) {
        const expectedElementsOfList = removeHeaderSeparatorLine(pExpectedElementsOfList);
        cy.uuvFindByRole("treegrid", { name: expectedListName })
            .uuvFoundedElement()
            .should("exist")
            .within(() => {
                expectTableToHaveContent(expectedElementsOfList, "gridcell");
            });
    }
);


/**
 * Checks that there is a table with the specified [name](https://russmaxdesign.github.io/html-elements-names/) containing list items.<br/> <u>Example</u>\n```gherkin\nWhen I visit path "https://e2e-test-quest.github.io/simple-webapp/table.html"\nThen I should see a table named "test-list" and containing\n| Company                       | Contact          | Country |\n| ----------------------------- | ---------------- | ------- |\n| Alfreds Futterkiste           | Maria Anders     | Germany |\n| Centro comercial Moctezuma    | Francisco Chang  | Mexico  |\n| Ernst Handel                  | Roland Mendel    | Austria |\n| Island Trading                | Helen Bennett    | UK      |\n| Laughing Bacchus Winecellars  | Yoshi Tannamuri  | Canada  |\n| Magazzini Alimentari Riuniti  | Giovanni Rovelli | Italy   |\n```
 * */
Then(
    `I should see a table named {string} and containing`,
    function(expectedListName: string, pExpectedElementsOfList: DataTable) {
        const expectedElementsOfList = removeHeaderSeparatorLine(pExpectedElementsOfList);
        cy.uuvFindByRole("table", { name: expectedListName })
            .uuvFoundedElement()
            .should("exist")
            .within(() => {
                expectTableToHaveContent(expectedElementsOfList, "cell");
            });
    }
);

/**
 * Checks Html attributes of the selected element
 * */
Then(
 `I should see these attributes with values`,
  function(expectedAttributeList: DataTable) {
   cy.uuvCheckContextWithinFocusedElement().then((context) => {
     const elementToSelect = context.withinFocusedElement!;
     for (const currentIndex in expectedAttributeList.raw()) {
       const attributeName = expectedAttributeList.raw()[currentIndex][0];
       const attributeValue = expectedAttributeList.raw()[currentIndex][1];
       elementToSelect.then((response) => {
         assert.equal(response[0].getAttribute(attributeName), attributeValue);
       });
     }
   });
 }
);

/**
 * Checks that an Html element exists with the specified selector
 * */
Then(`I should see an element with selector {string}`, function(selector: string) {
  cy.get(selector).should("exist");
});

/**
 * Check that the current page have no accessibility issue for [axe-core](https://github.com/dequelabs/axe-core/blob/develop/doc/rule-descriptions.md)
 * */
Then(
 `I should not have any axe-core accessibility issue`,
  function() {
    cy.injectUvvA11y();
    cy.checkUvvA11y({
      reference: A11yReferenceEnum.WCAG_WEB
    });
 });

/**
 * Check that the current page have not critical accessibility issue for [axe-core](https://github.com/dequelabs/axe-core/blob/develop/doc/rule-descriptions.md)
 * */
Then(
 `I should not have any axe-core critical accessibility issue`,
  function() {
   cy.injectUvvA11y();
   cy.checkUvvA11y({
      reference: A11yReferenceEnum.WCAG_WEB,
      runnerOptions: {
        includedImpacts: ["critical"]
      }
   });
 });

/**
 * Check that the current page have not accessibility issue for [axe-core](https://github.com/dequelabs/axe-core/blob/develop/doc/rule-descriptions.md) with one or more impacts in: 'minor','moderate','serious','critical'
 * */
Then(
 `I should not have any axe-core accessibility issue with {} impact(s)`,
  function(impacts: any) {
   cy.injectUvvA11y();
   cy.checkUvvA11y({
      reference: A11yReferenceEnum.WCAG_WEB,
      runnerOptions: {
        includedImpacts: [impacts]
      }
   });
 });

/**
 * Check that the current page have not accessibility issue for [axe-core](https://github.com/dequelabs/axe-core/blob/develop/doc/rule-descriptions.md) [with one or more Accessibility Standards](https://github.com/dequelabs/axe-core/blob/HEAD/doc/API.md#axe-core-tags)
 * */
Then(
 `I should not have any axe-core accessibility issue with accessibility standard(s) {}`,
  function(tags: any) {
   cy.injectUvvA11y();
   cy.checkUvvA11y({
      reference: A11yReferenceEnum.WCAG_WEB,
      runnerOptions: {
        runOnly: {
          type: "tag",
          values: [tags]
        }
      }
   });
 });

/**
 * Check that the current page have no accessibility issue for [axe-core](https://github.com/dequelabs/axe-core/blob/develop/doc/rule-descriptions.md) [with an option](https://github.com/dequelabs/axe-core/blob/HEAD/doc/API.md#options-parameter) on the specific [context](https://github.com/dequelabs/axe-core/blob/HEAD/doc/API.md#context-parameter)
 * */
Then(
 `I should not have any axe-core accessibility issue with context json fixture {} and option json fixture {}`,
  function(context: any, option: any) {
   cy.injectAxe();
   cy.fixture(context).then(context => {
     cy.fixture(option).then(option => {
       cy.checkA11y(context, option);
     });
   });
 });

/**
 * Check that the current page have no accessibility issue for [axe-core](https://github.com/dequelabs/axe-core/blob/develop/doc/rule-descriptions.md) [with an option](https://github.com/dequelabs/axe-core/blob/HEAD/doc/API.md#options-parameter)
 * */
Then(
 `I should not have any axe-core accessibility issue with option json fixture {}`,
  function(option: any) {
   cy.injectUvvA11y();
   cy.fixture(option).then(data => {
    cy.checkUvvA11y({
      reference: A11yReferenceEnum.WCAG_WEB,
      runnerOptions: data
    });
   });
 });


/**
 * Check that the current page have no [accessibility issue](https://accessibilite.numerique.gouv.fr/methode/criteres-et-tests/) based on RGAA standards
 * */
Then(
 `I should not have any rgaa accessibility issue`,
  function() {
   cy.injectUvvA11y();
   cy.checkUvvA11y({
    reference: A11yReferenceEnum.RGAA
   });
 });

Then(
 `I should have the following result based on the rgaa reference`,
  function(expectedResult: string) {
   cy.injectUvvA11y();
   cy.checkUvvA11y({
    reference: A11yReferenceEnum.RGAA,
    expectedResult: {
      value: JSON.parse(expectedResult)
    }
   });
 });

Then(
 `I should have the following partial result based on the rgaa reference`,
  function(expectedResult: string) {
   cy.injectUvvA11y();
   cy.checkUvvA11y({
    reference: A11yReferenceEnum.RGAA,
    expectedResult: {
      value: JSON.parse(expectedResult),
      isContainsMode: true
    }
   });
});

function haveKeyBoardFocused() {
  return Cypress.$(":focus").length > 0;
}

function type(textToType: string) {
  cy.uuvCheckContextWithinFocusedElement(true).then((context) => {
    if (context.withinFocusedElement) {
      context.withinFocusedElement!.type(textToType);
    } else if (haveKeyBoardFocused()) {
      cy.focused().type(textToType);
    }
  });
}
