import React from "react";
import { shallow } from "enzyme";
import GameCreationForm from "../components/util/GameCreationForm";
import { URBAN } from "../domain/genMethods";
import { FROZEN } from "../domain/ruleSets";

jest.mock("../domain/apiMethods");
jest.mock("../hooks/useCountryLookup");

import { createGame } from "../domain/apiMethods";
import useCountryLookup from "../hooks/useCountryLookup";

describe("GameCreationForm", () => {
  it("renders", () => {
    useCountryLookup.mockReturnValue("country-lookup");
    const afterCreate = jest.fn();
    const rendered = shallow(<GameCreationForm afterCreate={afterCreate} />);
    expect(rendered).toMatchSnapshot();
  });

  it("creates a game", async () => {
    useCountryLookup.mockReturnValue("country-lookup");
    createGame.mockReturnValue("test-game-id");
    const afterCreate = jest.fn();
    const rendered = shallow(<GameCreationForm afterCreate={afterCreate} />);
    await rendered.find("button").first().simulate("click");
    expect(createGame).toHaveBeenCalled();
    expect(afterCreate).toHaveBeenCalledWith("test-game-id");
  });

  it("does nothing after creating a game if no afterCreate given", async () => {
    useCountryLookup.mockReturnValue("country-lookup");
    createGame.mockReturnValue("test-game-id");
    const rendered = shallow(<GameCreationForm />);
    await rendered.find("button").first().simulate("click");
    expect(createGame).toHaveBeenCalled();
  });

  it("handles error creating a game", async () => {
    useCountryLookup.mockReturnValue("country-lookup");
    createGame.mockImplementation(() => {
      throw new Error();
    });
    const afterCreate = jest.fn();
    const rendered = shallow(<GameCreationForm afterCreate={afterCreate} />);
    await rendered.find("button").first().simulate("click");
    expect(createGame).toHaveBeenCalled();
    expect(afterCreate).not.toHaveBeenCalled();
    expect(rendered).toMatchSnapshot();
  });

  it("can have the error modal closed", async () => {
    useCountryLookup.mockReturnValue("country-lookup");
    createGame.mockImplementation(() => {
      throw new Error();
    });
    const rendered = shallow(<GameCreationForm />);
    await rendered.find("button").first().simulate("click");
    rendered.find("ErrorModal").first().prop("onClose")();
    expect(rendered).toMatchSnapshot();
  });

  it("can have presets selected", () => {
    useCountryLookup.mockReturnValue("country-lookup");
    const rendered = shallow(<GameCreationForm />);
    rendered.find("Dropdown").first().prop("onSelect")({
      timer: 30,
      rounds: 3,
      countryLock: "us",
      genMethod: URBAN,
      ruleSet: FROZEN,
    });
    expect(rendered).toMatchSnapshot();
  });
});
