import { NewsActions, SET_NEWS, ADD_NEWS, REMOVE_NEW, SAVE_NEW } from './news.actions';
import { New } from "../model/New.model";
import { AppState } from 'src/app/store/app.reducers';

export interface NewsFeatureState extends AppState{
    news: NewsState;
}

export interface NewsState{
    news: New[];
}

const initialState: NewsState = {
    news: null
}

export function newsReducers(state = initialState, action: NewsActions){
    switch(action.type){
        case SET_NEWS:
            return {
                ...state,
                news: action.news
            }
        case ADD_NEWS:
            return {
                ...state,
                news: state.news ? [...state.news, ...action.news] : action.news
            }
        case REMOVE_NEW:
            let news: New[] = state.news.filter((item: New) => item.id !== action.id);
            return {
                ...state,
                news: news
            }
        case SAVE_NEW:
            let updatedNews: New[] = state.news;
            let existingNewIndex: number = state.news.findIndex((newItem: New) => newItem.id === action.newItem.id);
            existingNewIndex > -1 ? updatedNews[existingNewIndex] = action.newItem : updatedNews.unshift(action.newItem);
            return {
                ...state,
                news: updatedNews
            }
        default:
            return state;
    }
}