import { renderHook } from "@testing-library/react-hooks";

jest.useFakeTimers();

jest.mock("@applicaster/zapp-react-native-utils/reactHooks/navigation", () => ({
  useIsScreenActive: () => true,
}));

const { useFeedRefresh, feedRefreshLogger } = require("..");

describe("useFeedRefresh", () => {
  const reloadData = jest.fn();

  const component = {
    id: "foo",
    rules: { enable_data_refreshing: true, refreshing_interval: 61 },
  };

  it("Calls reloadData after passed time lapses", () => {
    renderHook(() => useFeedRefresh({ reloadData, component }));

    expect(reloadData).not.toBeCalled();
    jest.runOnlyPendingTimers();
    expect(reloadData).toBeCalled();
  });

  it("Logs warning message if refresh time set below minimum value", () => {
    const loggerSpy = jest.spyOn(feedRefreshLogger, "warning");

    renderHook(() =>
      useFeedRefresh({
        reloadData,
        component: {
          ...component,
          rules: { enable_data_refreshing: true, refreshing_interval: 2 },
        },
      })
    );

    expect(loggerSpy).toBeCalled();
  });

  it("Calls reloadData on a Component that had a timer setup and was re-mounted", () => {
    reloadData.mockReset();

    // it is not called before rendering hook"
    expect(reloadData).not.toBeCalled();

    // it is not called when rendering new component (Not previously rendered)
    renderHook(() =>
      useFeedRefresh({ reloadData, component: { ...component, id: "bar" } })
    );

    expect(reloadData).not.toBeCalled();

    // it is called when rendering previously rendered component",
    renderHook(() => useFeedRefresh({ reloadData, component }));
    expect(reloadData).toBeCalled();
  });

  it("Doesn't refresh data when enable_data_refreshing if false", () => {
    reloadData.mockReset();

    renderHook(() =>
      useFeedRefresh({
        reloadData,
        component: { ...component, rules: { enable_data_refreshing: false } },
      })
    );

    jest.runOnlyPendingTimers();

    expect(reloadData).not.toBeCalled();
  });
});
