// ***********************************************
// 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) => { ... })

// ***********************************************
// 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 is will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })

const _ = Cypress._;

Cypress.Commands.add("manageCommand", (command, preCommand = "") => {
  const execCommand = `${preCommand} python server/manage.py ${command} --settings=config.settings.test_cypress`;
  console.log(execCommand);
  // hack to add my asdf python instance to the path
  // so I can run the test directly from within IntelliJ
  let pythonPaths = [
    "/Users/daniel/workspace/vbv_lernwelt/.direnv/python-3.10.6/bin",
    "/Users/eliabieri/iterativ/vbv_lernwelt/.direnv/python-3.10.6/bin",
  ];
  let bashCommand = `PATH=${pythonPaths.join(":")}:$PATH && ${execCommand}`;
  return cy
    .exec(`bash -c "${bashCommand}"`, {
      failOnNonZeroExit: true,
    })
    .then((result) => {
      if (result.code) {
        throw new Error(`Execution of "${command}" failed
      Exit code: ${result.code}
      Stdout:\n${result.stdout}
      Stderr:\n${result.stderr}`);
      }
    });
});

Cypress.Commands.add("manageShellCommand", (command) => {
  return cy.manageCommand(`shell -c '${command}'`);
});

function loadObjectJson(key, value, djangoModelPath, serializerModelPath) {
  const djangoModel = _.last(djangoModelPath.split("."));
  const djangoModelImportPath = _.initial(djangoModelPath.split(".")).join(".");
  const serializerModel = _.last(serializerModelPath.split("."));
  const serializerModelImportPath = _.initial(
    serializerModelPath.split(".")
  ).join(".");

  let filterPart = `${key}=${value}`;
  if (_.isArray(key)) {
    filterPart = _.zip(key, value)
      .map(([k, v]) => {
        return `${k}=${v}`;
      })
      .join(",");
  }

  const command = `from ${djangoModelImportPath} import ${djangoModel};
    from ${serializerModelImportPath} import ${serializerModel};
    from vbv_lernwelt.core.serializers import create_json_from_objects;
    object = ${djangoModel}.objects.filter(${filterPart}).first();
    print(create_json_from_objects(object, ${serializerModel}, many=False));
    exit();
  `.replace(/(?:\r\n|\r|\n)/g, "");
  return cy.manageShellCommand(command).then((result) => {
    const objectJson = JSON.parse(result.stdout);
    console.log(objectJson);
    return objectJson;
  });
}

Cypress.Commands.add("loadAssignmentCompletion", (key, value) => {
  return loadObjectJson(
    key,
    value,
    "vbv_lernwelt.assignment.models.AssignmentCompletion",
    "vbv_lernwelt.assignment.serializers.AssignmentCompletionSerializer"
  );
});

Cypress.Commands.add("makeSelfEvaluation", (answers) => {
  for (let i = 0; i < answers.length; i++) {
    const answer = answers[i];
    if (answer) {
      cy.get('[data-cy="success"]').click();
    } else {
      cy.get('[data-cy="fail"]').click();
    }
    if (i < answers.length - 1) {
      cy.get('[data-cy="next-step"]').click({ force: true });
    } else {
      cy.get('[data-cy="complete-and-continue"]').click({ force: true });
    }
  }
});

// Cypress.Commands.add('loadApiClientRequestResponseLog', (key, value) => {
//   return loadObjectJson(
//     key,
//     value,
//     'myservice.apps.apiclient.models.ApiClientRequestResponseLog',
//     'myservice.apps.apiclient.serializers.ApiClientRequestResponseLogSerializer'
//   );
// });

Cypress.Commands.add("learningContentMultiLayoutNextStep", () => {
  return cy.get('[data-cy="next-step"]').click({ force: true });
});

Cypress.Commands.add("learningContentMultiLayoutPreviousStep", () => {
  return cy.get('[data-cy="previous-step"]').click({ force: true });
});

Cypress.Commands.add("testLearningContentTitle", (title) => {
  return cy.get('[data-cy="lc-title"]').should("contain", title);
});

Cypress.Commands.add("testLearningContentSubtitle", (subtitle) => {
  return cy.get('[data-cy="lc-subtitle"]').should("contain", subtitle);
});
