import { combineReducers } from 'redux';

import { BaseVideoDetails } 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 { VideoType } from 'mweb/common/reducers/data/baseVideoDetails';

export interface ClipDetails extends BaseVideoDetails {
  readonly url: string;
  readonly videoType: VideoType.Clip;
}

export interface MutableClipDetailsMap {
  [clipID: string]: ClipDetails;
}

export type ClipDetailsMap = Readonly<MutableClipDetailsMap>;

export interface ClipsState {
  readonly clipDetails: ClipDetailsMap;
  readonly clipsByChannelLoadStatus: ClipsByChannelLoadStatusMap;
}

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

export function clipDetails(
  state: ClipDetailsMap = {},
  action: Action,
): ClipDetailsMap {
  switch (action.type) {
    case CHANNELS_DATA_CHANNEL_LOADED_ACTION_TYPE:
      if (!action.payload.clips) {
        return state;
      }
      return {
        ...state,
        ...action.payload.clips,
      };
    default:
      return state;
  }
}
function clipsByChannelLoadStatus(
  state: ClipsByChannelLoadStatusMap = {},
  action: Action,
): ClipsByChannelLoadStatusMap {
  switch (action.type) {
    case CHANNELS_DATA_CHANNEL_LOADED_ACTION_TYPE:
      if (!action.payload.clips) {
        return state;
      }
      return {
        ...state,
        [action.payload.channel.name]: true,
      };
    default:
      return state;
  }
}

export function buildClipsReducer(): (
  state: ClipsState | undefined,
  action: Action,
) => ClipsState {
  return combineReducers<ClipsState>({
    clipDetails,
    clipsByChannelLoadStatus,
  });
}
