import { getTopContent, ITopContentBody, ITopContentCategory } from '@rh-support/api';
import { IAction } from '@rh-support/types';
import map from 'lodash/map';

type IActionType = IAction<TopContentConstants, ITopContentState>;

// Constants
export enum TopContentConstants {
    requestTopContent = 'requestTopContent',
    receivedTopContent = 'receivedTopContent',
    receivedTopContentError = 'receivedTopContentError'
}

export const initialTopContentState: ITopContentState = {
    isLoadingTopContent: true,
    isLoadingTopContentError: false,
    topContentResponse: []
};

export interface ITopContentState {
    isLoadingTopContent: boolean;
    isLoadingTopContentError: boolean;
    topContentResponse: ITopContentCategory[];
}

// Resucers
export const topContentReducer = (state: ITopContentState, action: IActionType): ITopContentState => {
    switch (action.type) {
        case TopContentConstants.requestTopContent: {
            return { ...state, topContentResponse: [], isLoadingTopContent: true, isLoadingTopContentError: false };
        }
        case TopContentConstants.receivedTopContent: {
            return { ...state, topContentResponse: action.payload.topContentResponse, isLoadingTopContent: false, isLoadingTopContentError: false };
        }
        case TopContentConstants.receivedTopContentError: {
            return { ...state, topContentResponse: [], isLoadingTopContent: false, isLoadingTopContentError: true };
        }
        default: {
            return state;
        }
    }
};

export const fetchTopContent = async (dispatch: any, body: Partial<ITopContentBody>) => {
    dispatch({ type: TopContentConstants.requestTopContent });
    try {
        const response = await getTopContent(body);

        // remove items with empty title
        let categories = map(response.categories, (category) => {
            category.items = category.items.filter((item) => item.title !== '');
            return category;
        });

        // remove catagories with empty items
        categories = categories.filter((category) => category.items.length !== 0);

        dispatch({ type: TopContentConstants.receivedTopContent, payload: { topContentResponse: categories } });
    } catch (error) {
        dispatch({ type: TopContentConstants.receivedTopContentError });
    }
};
