/**
 * This file is part of Anis Client.
 *
 * @copyright Laboratoire d'Astrophysique de Marseille / CNRS
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import { createReducer, on } from '@ngrx/store';

import * as detailActions from '../actions/detail.actions';

/**
 * Interface for detail state.
 *
 * @interface State
 */
export interface State {
    object: any;
    objectIsLoading: boolean;
    objectIsLoaded: boolean;
    spectraCSV: string;
    spectraIsLoading: boolean;
    spectraIsLoaded: boolean;
}

export const initialState: State = {
    object: null,
    objectIsLoading: false,
    objectIsLoaded: false,
    spectraCSV: null,
    spectraIsLoading: false,
    spectraIsLoaded: false,
};

export const detailReducer = createReducer(
    initialState,
    on(detailActions.retrieveObject, state => ({
        ...state,
        objectIsLoading: true,
        objectIsLoaded: false
    })),
    on(detailActions.retrieveObjectSuccess, (state, { object }) => ({
        ...state,
        objectIsLoading: false,
        objectIsLoaded: true,
        object
    })),
    on(detailActions.retrieveObjectFail, state => ({
        ...state,
        objectIsLoading: false
    })),
    on(detailActions.retrieveSpectra, state => ({
        ...state,
        spectraIsLoading: true,
        spectraIsLoaded: false
    })),
    on(detailActions.retrieveSpectraSuccess, (state, { spectraCSV }) => ({
        ...state,
        spectraIsLoading: false,
        spectraIsLoaded: true,
        spectraCSV
    })),
    on(detailActions.retrieveSpectraFail, state => ({
        ...state,
        spectraIsLoading: false
    }))
);

export const selectObject = (state: State) => state.object;
export const selectObjectIsLoading = (state: State) => state.objectIsLoading;
export const selectObjectIsLoaded = (state: State) => state.objectIsLoaded;
export const selectSpectraCSV = (state: State) => state.spectraCSV;
export const selectSpectraIsLoading = (state: State) => state.spectraIsLoading;
export const selectSpectraIsLoaded = (state: State) => state.spectraIsLoaded;