import { Action } from 'mweb/common/actions/root';
import { PLATFORM_SWITCHED_TO_SERVER_ACTION_TYPE } from 'mweb/common/actions/platform';
import {
  NAVIGATION_UPDATED_LOCATION_ACTION_TYPE,
  PageviewEvent,
} from 'mweb/common/actions/navigation';
import {
  TRACKING_PARAMS_CAPTURED_ACTION_TYPE,
  TRACKING_PARAMS_CLEARED_ACTION_TYPE,
} from 'mweb/common/actions/tracking';
import { ChannelsDataPageLoadedEvent } from 'mweb/common/actions/data/channels';
import { GamesDataPageLoadedEvent } from 'mweb/common/actions/data/games';
import {
  EventDetailsPageEventSharedEvent,
  EventDetailsPageNotificationRequestedEvent,
} from 'mweb/common/actions/pages/eventDetails';
import { uniqueIDGenerator } from 'mweb/common/utils/uniqueIDs';

export type TrackedEvent =
  | ChannelsDataPageLoadedEvent
  | GamesDataPageLoadedEvent
  | EventDetailsPageEventSharedEvent
  | EventDetailsPageNotificationRequestedEvent
  | PageviewEvent;
export type EventList = TrackedEvent[];

export interface TrackingState {
  readonly content: string | undefined;
  readonly medium: string | undefined;
  readonly pageLoadID: string;
  readonly spadeURI: string;
}

const DEFAULT_APP_STATE: TrackingState = {
  content: undefined,
  medium: undefined,
  pageLoadID: '',
  spadeURI: '',
};

const PAGE_LOAD_UNIQUE_ID_LENGTH = 64;

export function tracking(
  state: TrackingState = DEFAULT_APP_STATE,
  action: Action,
): TrackingState {
  switch (action.type) {
    case PLATFORM_SWITCHED_TO_SERVER_ACTION_TYPE:
      return {
        ...state,
        spadeURI: action.payload.spadeURI,
      };

    case NAVIGATION_UPDATED_LOCATION_ACTION_TYPE:
      return {
        ...state,
        pageLoadID: uniqueIDGenerator(PAGE_LOAD_UNIQUE_ID_LENGTH),
      };
    case TRACKING_PARAMS_CAPTURED_ACTION_TYPE:
      return {
        ...state,
        medium: action.payload.tt_medium || state.medium,
        content: action.payload.tt_content || state.content,
      };
    case TRACKING_PARAMS_CLEARED_ACTION_TYPE:
      return {
        ...state,
        content: undefined,
        medium: undefined,
      };
    default:
      return state;
  }
}
