import {createReducer} from '@ngrx/store';
import {All, CustomAuthActionTypes, CustomLogInAction} from '../actions/custom-login-page.action';


export interface CustomState {
    // is a user authenticated?
    isAuthenticated: boolean;
    // if authenticated, there should be a user object
    user: any;
    // error message
    errorMessage: string | null;
}

export const initialState: CustomState = {
    isAuthenticated: false,
    user: null,
    errorMessage: null
};


export function reducer(state = initialState, action: All): CustomState {
    switch (action.type) {
        case CustomAuthActionTypes.LOGIN_SUCCESS: {
            console.log('library state inside reducer for action ' + action.type);
            console.log(state);
            console.log(action.payload);
            return {
                ...state,
                isAuthenticated: true,
                user: action.payload,
                errorMessage: null
            };
        }
        case CustomAuthActionTypes.LOGIN_ERROR: {
            console.log('library state inside reducer for action ' + action.type);
            console.log(state);
            console.log(action.payload);
            return {
                ...state,
                isAuthenticated: false,
                user: action.payload,
                errorMessage: action.payload.errorMessage
            };
        }

        case CustomAuthActionTypes.LOGOUT: {
            console.log('library state inside reducer for action ' + action.type);
            return {
                ...state,
                isAuthenticated: false,
                user: null,
                errorMessage: null
            };
        }

        default: {
            console.log('library default');
            console.log(state);
            return state;
        }
    }
}
