import { get } from 'lodash';
import createReducer from 'bitbucket/internal/bbui/utils/create-reducer';
import {
    CLEAR_REPOSITORIES,
    LOAD_REPOSITORIES,
    LOAD_REPOSITORIES_FAILURE,
    LOAD_REPOSITORIES_SUCCESS,
} from '../actions';
import { RECENT } from '../repository-type';

const DEFAULT_REPOSITORY_LIST = RECENT;

/**
 * Handles load repositories optimistic action
 * @param {Object} state
 * @param {Object} action
 * @param {string?} action.meta.query - for a search, the search query
 * @param {RepositoryType} action.meta.repoType
 * @returns {Object}
 */
function loadRepositories(state = {}, action) {
    const newState = {
        ...state,
        repositoriesLoading: true,
    };

    // If we're loading repositories for a new query, then don't display any repos (just the spinner)
    if (get(action, 'meta.query') !== get(state, 'currentQuery')) {
        newState.activeRepositoryList = null;
    } else {
        newState.activeRepositoryList = get(action, 'meta.repoType', null);
    }

    return newState;
}

/**
 * Handles load repository completion, and clear repository actions.
 * @param {Object} state
 * @param {Object} action
 * @param {string?} action.meta.query - for a search, the query triggered this action
 * @param {RepositoryType} action.meta.repoType - repostory list type that applies to this action
 * @returns {Object}
 */
function updateRepositories(state = {}, action) {
    return {
        ...state,
        repositoriesLoading: false,
        currentQuery: get(action, 'meta.query'),
        activeRepositoryList: action.type === CLEAR_REPOSITORIES ? DEFAULT_REPOSITORY_LIST : get(action, 'meta.repoType'),
    };
}

export default createReducer({}, {
    [LOAD_REPOSITORIES]: loadRepositories,
    [LOAD_REPOSITORIES_FAILURE]: updateRepositories,
    [LOAD_REPOSITORIES_SUCCESS]: updateRepositories,
    [CLEAR_REPOSITORIES]: updateRepositories
});