import { TEST_STUDENT1_USER_ID } from "../../consts";
import { login } from "../helpers";

describe("assignmentTrainer.cy.js", () => {
  beforeEach(() => {
    cy.manageCommand("cypress_reset --create-completion");
    login("test-trainer1@example.com", "test");
  });

  it("can open cockpit assignment page and open user assignment", () => {
    cy.visit("/course/test-lehrgang/cockpit/assignment");

    cy.get('[data-cy="Student1"]').should("contain", "Ergebnisse abgegeben");
    cy.get('[data-cy="Student1"]').find('[data-cy="show-results"]').click();

    cy.get('[data-cy="student-submission"]').should("contain", "Ergebnisse");
    cy.get('[data-cy="student-submission"]').should("contain", "Student1");
  });

  it("can start evaluation and store evaluation results", () => {
    cy.visit("/course/test-lehrgang/cockpit/assignment");

    cy.get('[data-cy="Student1"]').find('[data-cy="show-results"]').click();

    cy.get('[data-cy="start-evaluation"]').click();
    cy.get('[data-cy="evaluation-task"]').should(
      "contain",
      "Beurteilungskriterium 1 / 5"
    );

    // without text input the button should be disabled
    cy.get('[data-cy="next-step"]').should("be.disabled");

    // with text you can continue
    cy.get('[data-cy="subtask-4"]').click();
    cy.get('[data-cy="reason-text"]').type("Gut gemacht!");
    // wait for debounce
    cy.wait(500);
    cy.get('[data-cy="next-step"]').click();

    cy.get('[data-cy="evaluation-task"]').should(
      "contain",
      "Beurteilungskriterium 2 / 5"
    );
    cy.get('[data-cy="subtask-2"]').click();
    cy.get('[data-cy="reason-text"]').type("Nicht so gut");
    cy.wait(500);

    // revisit step 1 will show stored data
    cy.get('[data-cy="previous-step"]').click();
    cy.get('[data-cy="reason-text"]')
      .find("textarea")
      .should("have.value", "Gut gemacht!");

    // even after reload
    cy.reload();
    cy.get('[data-cy="reason-text"]')
      .find("textarea")
      .should("have.value", "Gut gemacht!");

    // it can access step directly via url
    cy.url().then((url) => {
      const step2Url = url.replace("step=1", "step=2");
      console.log(step2Url);
      cy.visit(step2Url);
    });

    cy.get('[data-cy="reason-text"]')
      .find("textarea")
      .should("have.value", "Nicht so gut");

    // load AssignmentCompletion from DB and check
    cy.loadAssignmentCompletion(
      "assignment_user_id",
      TEST_STUDENT1_USER_ID
    ).then((ac) => {
      expect(ac.completion_status).to.equal("EVALUATION_IN_PROGRESS");
      expect(JSON.stringify(ac.completion_data)).to.include("Nicht so gut");
      expect(Cypress._.values(ac.completion_data)).to.deep.include({
        expert_data: { points: 2, text: "Nicht so gut" },
      });
      expect(Cypress._.values(ac.completion_data)).to.deep.include({
        expert_data: { points: 4, text: "Gut gemacht!" },
      });
    });
  });
});
