import { AppState } from 'src/app/store/app.reducers';
import { AttacksActions, SET_ATTACKS_LIST, ADD_ATTACK, UPDATE_ATTACK, REMOVE_ATTACK, UPDATE_SEARCH, UPDATE_SORT } from "./attacks.actions";
import { Attack } from '../model/attack.model';

export interface AttacksFeatureState extends AppState{
    attacks: AttacksState;
}

export interface Sort{
    by: String;
    reverse: Boolean; 
}

export interface AttacksState{
    attacks: Attack[];
    sort: Sort;
    search: String;
}

const initialState: AttacksState = {
    attacks: null,
    sort: {
        by: "date",
        reverse: true
    },
    search: null
}

export function attacksReducers(state = initialState, action: AttacksActions){
    switch(action.type){
        case SET_ATTACKS_LIST:
            return {
                ...state,
                attacks: action.attacks
            }
        case ADD_ATTACK:
            return {
                ...state,
                attacks: [...state.attacks, action.attack]
            };
        case UPDATE_ATTACK:
            let index: number = state.attacks.findIndex((attack: Attack) => { return attack.id === action.attack.id });
            let attacks = state.attacks;
            attacks[index] = action.attack
            return {
                ...state,
                attacks: index ? attacks : state.attacks
            }
        case REMOVE_ATTACK:
            return {
                ...state,
                attacks: state.attacks.filter((attack: Attack) => { return attack.id !== action.id})
            }
        case UPDATE_SEARCH:
            return {
                ...state,
                search: action.search
            }
        case UPDATE_SORT:
            return {
                ...state,
                sort: {
                    by: action.by,
                    reverse: action.reverse
                }
            }
        default:
            return state;
    }
}