import {
    SET_VISIBLE,
    SET_WORK_IN_PROGRESS,
    CUSTOM_ERROR,
    DISMISS_ERROR,
    SHOW_ALERT,
    DISMISS_ALERT,
    CONFIGURATION_NOT_FOUND_ERROR,
    SET_VISIBLE_WITH_COUNTER,
} from './Actions';

import * as apiActions from '../Actions';

const initialState = {
    visibilityMap: {},
    visibilityMapCount: {},
    backgroundWorkMap: {},
    error: null,
    message: null,
};

export function errorHandler(state, action) {
    switch (action.type) {
        case apiActions.NETWORK_ERROR:
        case apiActions.REQUEST_ERROR:
        case CUSTOM_ERROR:
        case CONFIGURATION_NOT_FOUND_ERROR: {
            return {
                ...state,
                error: {
                    ...action.error,
                    type: action.type,
                    source: action.source,
                },
            };
        }

        case DISMISS_ERROR: {
            return {
                ...state,
                error: null,
            };
        }

        default:
            return state;
    }
}

const UIReducer = (state = initialState, action = {}) => {
    switch (action.type) {
        case SET_VISIBLE: {
            return {
                ...state,
                visibilityMap: {
                    ...state.visibilityMap,
                    [action.name]: action.show,
                },
            };
        }

        case SET_VISIBLE_WITH_COUNTER: {
            const stackCount = Math.max(
                (state.visibilityMapCount[action.name] || 0) + (action.show ? 1 : -1),
                0
            );
            return {
                ...state,
                visibilityMap: {
                    ...state.visibilityMap,
                    [action.name]: stackCount > 0,
                },
                visibilityMapCount: {
                    ...state.visibilityMapCount,
                    [action.name]: stackCount,
                },
            };
        }

        case SET_WORK_IN_PROGRESS: {
            return {
                ...state,
                backgroundWorkMap: {
                    ...state.backgroundWorkMap,
                    [action.name]: action.value,
                },
            };
        }

        case SHOW_ALERT: {
            return {
                ...state,
                message: action.message,
            };
        }

        case DISMISS_ALERT: {
            return {
                ...state,
                message: null,
            };
        }

        default:
            return errorHandler(state, action);
    }
};

export default UIReducer;
