import { combineReducers } from 'redux';

import {
  BaseVideoDetails,
  VODVideoType,
} from 'mweb/common/reducers/data/baseVideoDetails';
import { CHANNELS_DATA_CHANNEL_LOADED_ACTION_TYPE } from 'mweb/common/actions/data/channels';
import { Action } from 'mweb/common/actions/root';
import { VODS_DATA_VOD_LOADED_ACTION_TYPE } from 'mweb/common/actions/data/vods';
import { EVENTS_DATA_EVENT_LOADED_ACTION_TYPE } from 'mweb/common/actions/data/events';

export interface VODDetails extends BaseVideoDetails {
  readonly description: string | undefined;
  readonly videoType: VODVideoType | undefined;
}

export interface MutableVODDetailsMap {
  [vodID: string]: VODDetails;
}

export type VODDetailsMap = Readonly<MutableVODDetailsMap>;

export interface VODsState {
  readonly vodDetails: VODDetailsMap;
  readonly vodsByChannelLoadStatus: VodsByChannelLoadStatusMap;
}

export interface VodsByChannelLoadStatusMap {
  readonly [channel: string]: true;
}

export function vodDetails(
  state: VODDetailsMap = {},
  action: Action,
): VODDetailsMap {
  switch (action.type) {
    case VODS_DATA_VOD_LOADED_ACTION_TYPE:
    case EVENTS_DATA_EVENT_LOADED_ACTION_TYPE:
      if (!action.payload.vod) {
        return state;
      }
      return {
        ...state,
        [action.payload.vod.id]: action.payload.vod,
      };
    case CHANNELS_DATA_CHANNEL_LOADED_ACTION_TYPE:
      if (!action.payload.videos) {
        return state;
      }
      return {
        ...state,
        ...action.payload.videos,
      };
    default:
      return state;
  }
}

export function vodsByChannelLoadStatus(
  state: VodsByChannelLoadStatusMap = {},
  action: Action,
): VodsByChannelLoadStatusMap {
  switch (action.type) {
    case CHANNELS_DATA_CHANNEL_LOADED_ACTION_TYPE:
      if (!action.payload.videos) {
        return state;
      }
      return {
        ...state,
        [action.payload.channel.name]: true,
      };
    default:
      return state;
  }
}

export function buildVODsReducer(): (
  state: VODsState | undefined,
  action: Action,
) => VODsState {
  return combineReducers<VODsState>({
    vodDetails,
    vodsByChannelLoadStatus,
  });
}
