import expect from 'expect';

import { Action } from 'mweb/common/actions/root';
import { resetPageReducerOnNavigation } from 'mweb/common/utils/resetPageReducerOnNavigation';
import { NAVIGATION_UPDATED_LOCATION_ACTION_TYPE } from 'mweb/common/actions/navigation';
import { Location } from 'mweb/common/reducers/app';
import { PLATFORM_SWITCHED_TO_SERVER_ACTION_TYPE } from 'mweb/common/actions/platform';

interface FakeState {
  motto: string;
}

describe('resetPageReducerOnNavigation', () => {
  const DEFAULT_FAKE_STATE: FakeState = {
    motto: '',
  };

  function fakeReducer(
    state: FakeState = DEFAULT_FAKE_STATE,
    action: Action,
  ): FakeState {
    switch (action.type) {
      case PLATFORM_SWITCHED_TO_SERVER_ACTION_TYPE:
        return { motto: 'Whatever, I do what I want!' };
      default:
        return state;
    }
  }

  const resettingReducer = resetPageReducerOnNavigation(
    fakeReducer,
    Location.DirectoryMainGame,
  );

  const initialState: FakeState = { motto: 'YOLO!' };

  describe('navigation update', () => {
    it('does not trigger reset when new location is target location', () => {
      const action: Action = {
        type: NAVIGATION_UPDATED_LOCATION_ACTION_TYPE,
        payload: {
          location: Location.DirectoryMainGame,
          intent: '',
          referrer: document.referrer,
        },
      };

      expect(resettingReducer(initialState, action)!.motto).toEqual('YOLO!');
    });

    it('does happen when new location is not target location', () => {
      const action: Action = {
        type: NAVIGATION_UPDATED_LOCATION_ACTION_TYPE,
        payload: {
          location: Location.DirectoryGame,
          intent: '',
          referrer: document.referrer,
        },
      };

      expect(resettingReducer(initialState, action)!.motto).toEqual('');
    });
  });

  describe('pass through', () => {
    it('works for non-navigation update actions', () => {
      const action: Action = {
        type: PLATFORM_SWITCHED_TO_SERVER_ACTION_TYPE,
        payload: {
          gitHash: 'a',
          spadeURI: 'b',
        },
      };

      expect(resettingReducer(initialState, action)!.motto).toEqual(
        'Whatever, I do what I want!',
      );
    });

    it('allows returning default when initial state is undefined', () => {
      const action: Action = { type: 'NOOP' };
      expect(resettingReducer(undefined, action)!.motto).toEqual('');
    });
  });
});
