import React from "react";
import {render, unmountComponentAtNode} from "react-dom";
import {act} from "react-dom/test-utils";
import {Table} from "../src/control";
import * as test_data from "./test_users.json"
import axios from "axios";
import MockAdapter from "axios-mock-adapter";

let mock;
let container = null
beforeEach(() => {
  mock = new MockAdapter(axios);
  mock.onGet('/api/users').reply(200, test_data)
  container = document.createElement('div')
  container.id = "table"
  document.body.appendChild(container)
})

afterEach(() => {
  unmountComponentAtNode(container);
  mock.restore()
  container.remove();
  container = null;
});

it("has only main table row without axios request", () => {
  act(() => {
    render(<Table/>, container);
  });
  let tbody = container.querySelector("#tbody")
  expect(tbody.getElementsByTagName('tr').length).toBe(0);
});

it("shows valid number of free workplaces", async () => {
  await act(async () => {
    render(<Table/>, container)
  })
  let element = container.querySelector('#licences_remaining')
  let licences = Number(element.innerHTML.replace(/Свободных мест: /, ''))
  expect(licences).toEqual(1)
});

it("Pretext must be deleted on render", () => {
  act(() => {
    render(<Table/>, container)
  })
  expect(document.body).not.toContain(container.querySelector('#loading'))
});

it("has valid number of table rows with axios request", async () => {
  await act(async () => {
    render(<Table/>, container)
  })
  let tbody = container.querySelector("#tbody")
  expect(tbody.getElementsByTagName('tr').length)
    .toEqual(test_data.users.length + test_data.zendesk_users.length)
});

it("show valid number for engineers and light agents", async () => {
  await act(async () => {
    render(<Table/>, container)
  })
  let engineers = container.querySelector('#engineers')
  let agents = container.querySelector('#agents')
  expect(Number(engineers.textContent)).toEqual(test_data.engineers)
  expect(Number(agents.textContent)).toEqual(test_data.light_agents)
});

it("called one request on mount", async () => {
  let req = jest.spyOn(Table.prototype, "get_users")
  await act(async () => {
    render(<Table/>, container)
  })
  expect(req).toHaveBeenCalledTimes(1)
})
it("checkbox count equals users from db count", async () => {
  await act(async () => {
    render(<Table/>, container)
  })
  let tbody = container.querySelector("#tbody")
  let checkboxes = tbody.querySelectorAll("input[type='checkbox']")
  let users = test_data.users
  expect(checkboxes.length).toEqual(users.length)
})
