import { Reducer } from 'redux';

import * as Actions from './actions';
import { IPokemonSelectListState, PokemonSelectListActionTypes } from './types';

export const initialState : IPokemonSelectListState = {
    isLoading: true,
    activePokemonId: null,
    activePokemonForm: null,
    pokemonList: [],
    pokemonListFiltered: [],
    filterTerm: '',
    pokemonLeagueStats: {},
};

const reduceSetIsLoading = (
    state : IPokemonSelectListState,
    action : ReturnType<typeof Actions.setIsLoading>
) : IPokemonSelectListState => ({
    ...state,
    isLoading: action.payload.isLoading,
});

const reduceSetPokemonList = (
    state : IPokemonSelectListState,
    action : ReturnType<typeof Actions.setPokemonList>
) : IPokemonSelectListState => ({
    ...state,
    pokemonList: action.payload.pokemonList,
});

const reduceSetPokemonListFiltered = (
    state : IPokemonSelectListState,
    action : ReturnType<typeof Actions.setPokemonListFiltered>
) : IPokemonSelectListState => ({
    ...state,
    filterTerm: action.payload.filterTerm,
    pokemonListFiltered: action.payload.pokemonListFiltered,
});

const reduceSetActivePokemonId = (
    state : IPokemonSelectListState,
    action : ReturnType<typeof Actions.setActivePokemonId>
) : IPokemonSelectListState => ({
    ...state,
    activePokemonId: action.payload.activePokemonId,
    activePokemonForm: action.payload.activePokemonForm,
});

const reduceSetPokemonLeagueStats = (
    state : IPokemonSelectListState,
    action : ReturnType<typeof Actions.setPokemonLeagueStats>
) : IPokemonSelectListState => ({
    ...state,
    pokemonLeagueStats: {
        ...state.pokemonLeagueStats,
        [action.payload.pokemonId] : action.payload.pokemonLeagueStats,
    },
});

export const PokemonSelectListReducers : Reducer<IPokemonSelectListState> = (
    state : IPokemonSelectListState = initialState,
    action,
) : IPokemonSelectListState => {
    switch (action.type) {
        case PokemonSelectListActionTypes.SET_IS_LOADING:
            return reduceSetIsLoading(state, action as ReturnType<typeof Actions.setIsLoading>);
        case PokemonSelectListActionTypes.SET_POKEMON_LIST:
            return reduceSetPokemonList(state, action as ReturnType<typeof Actions.setPokemonList>);
        case PokemonSelectListActionTypes.SET_POKEMON_LIST_FILTERED:
            return reduceSetPokemonListFiltered(state, action as ReturnType<typeof Actions.setPokemonListFiltered>);
        case PokemonSelectListActionTypes.SET_ACTIVE_POKEMON_ID:
            return reduceSetActivePokemonId(state, action as ReturnType<typeof Actions.setActivePokemonId>);
        case PokemonSelectListActionTypes.SET_POKEMON_LEAGUE_STATS:
            return reduceSetPokemonLeagueStats(state, action as ReturnType<typeof Actions.setPokemonLeagueStats>);
        default:
            return state;
    }
};
