import React from 'react';
import { renderHook, act } from '@testing-library/react-hooks';
import { useQueryString } from './useQueryString.web';

const oldWindowLocation = window.location;
let eventMap: any = {};

beforeEach(() => {
   delete window.location;
   delete window.addEventListener;
   window.location = {} as any;
   window.location.pathname = '/';
   window.location.href = '';

   eventMap = {};
   window.addEventListener = function (event, cb): void {
      eventMap[event] = cb;
   };
});

afterEach(() => {
   window.location = oldWindowLocation;
});

test('useQueryString - resgatar query inicial', async () => {
   window.location.pathname = '/route';
   window.location.href = 'https://example.com.br/route?name=Veronica&gender=female';

   const { result, waitForNextUpdate } = renderHook(() => useQueryString());

   expect(result.current).toEqual({
      name: 'Veronica',
      gender: 'female',
   });
});

test('useQueryString - mudar query', async () => {
   window.location.pathname = '/route';
   window.location.href = 'https://example.com.br/route?name=Veronica&gender=female';

   const { result, waitForNextUpdate } = renderHook(() => useQueryString());

   expect(result.current).toEqual({
      name: 'Veronica',
      gender: 'female',
   });

   window.location.pathname = '/route';
   window.location.href = 'https://example.com.br/route?name=John&age=18';
   act(() => {
      eventMap.popstate();
   });

   expect(result.current).toEqual({
      age: '18',
      name: 'John',
   });
});

test('useQueryString - mudar query com rota definida NÃO deve mudar causar alterações', async () => {
   window.location.pathname = '/route';
   window.location.href = 'https://example.com.br/route?name=Veronica&gender=female';

   const { result, waitForNextUpdate } = renderHook(() => useQueryString('route'));

   expect(result.current).toEqual({
      name: 'Veronica',
      gender: 'female',
   });

   window.location.pathname = 'route2';
   window.location.href = 'https://example.com.br/route2?name=John&age=18';
   act(() => {
      eventMap.popstate();
   });

   expect(result.current).toEqual({
      name: 'Veronica',
      gender: 'female',
   });
});
