// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add("login", (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })

/* globals Cypress, cy, expect */

import 'cypress-localstorage-commands';

Cypress.Commands.add('login', () => {
  cy.fixture('admin.json').then(admin => {
    cy.get('#id_username').type(admin.username);
    cy.get('#id_username').should('have.value', admin.username);
    cy.get('#id_password').type(admin.password);
    cy.get('#id_password').should('have.value', admin.password);
    cy.get('.connection-btn').click();
    cy.location('pathname').should('include', '/authorize');
    cy.get('.accept-button').click();
    cy.location().should(location => {
      expect(location.pathname).to.eq('/');
    });
  });
});

Cypress.Commands.add('userLogin', () => {
  cy.visit('/');
  cy.location().should((loc) => {
    expect(loc.pathname).to.eq('/auth/login/');
  });
});

Cypress.Commands.add('encodeUrl', url => {
  const encodeIdReplacement = [
    ['~', '~~'],
    ['.', '~!'],
    [':', '~@'],
    ['/', '~_'],
  ];
  encodeIdReplacement.forEach(([char, repl]) => {
    url = url.split(char).join(repl);
  });
  return url;
});

Cypress.Commands.add('randomNum', () => {
  return Math.floor(1000 + Math.random() * 9000);
});

Cypress.Commands.add('nextYear', increment => {
  return new Date().getFullYear() + ( increment || 1 );
});