import get from 'lodash/get';
import flow from 'lodash/flow';
import { getConf } from '../../configuration';
import * as configuratorActionTypes from '../Configurator/Actions';
import { actionTypes as configurationModeActions } from './Actions';
import { getAvailableLicenses, getConfigurationModes } from './Selectors';

const getFirstAvailableConfigurationModeIdentifier = flow(
    item => (item.configurationModes || []).find(mode => get(mode, 'itemStatus.item_available')),
    mode => (mode ? mode.identifier : null)
);

const initialState = {
    availableModes: getConfigurationModes(),
    selectedMode: null,
    licenses: [],
};

function getPreselectedModeIfAvailable(availableModes, selectedMode = getConf('configurationMode')) {
    return !!selectedMode && availableModes[selectedMode] && selectedMode;
}

export default function configurationModeReducer(state = initialState, action = {}) {
    switch (action.type) {
        case configuratorActionTypes.RECEIVE_CONFIGURATION: {
            const item = get(action, 'data.item', {});
            const availableModes = getConfigurationModes(item);
            const selectedMode =
                getPreselectedModeIfAvailable(availableModes) ||
                (getConf('adminMode') === 'defaultoptions'
                    ? 'creator'
                    : getFirstAvailableConfigurationModeIdentifier(item));
            return {
                ...state,
                selectedMode,
                availableModes,
                licenses: getAvailableLicenses(action.data),
            };
        }
        case configurationModeActions.SELECT_CONFIGURATION_MODE: {
            const { mode } = action;
            return {
                ...state,
                selectedMode: state.availableModes[mode] ? mode : state.selectedMode,
            };
        }
        default:
            return state;
    }
}
