import produce from 'immer';
import { Fragment } from 'react';

export const initialState = {
    messages: [],
};

export default function reducer(state = initialState, action = {}) {
    return produce(state, draft => {
        switch (action.type) {
            case MESSAGE_ADD:
                draft.messages.push(action.payload);
                break;
            case MESSAGE_REMOVE:
                var found = draft.messages.find(v => v.id == action.payload);
                if(found) {
                    var index = draft.messages.indexOf(found);
                    if(index != -1) draft.messages.splice(index, 1);
                }
                break;
            case MESSAGE_HIDE:
                var found = draft.messages.find(v => v.id == action.payload);
                if(found) {
                    found.hide = true;
                }
                break;
        }
    });
}

export const MESSAGE_ADD = 'GLOBAL_MESSAGE/ADD';
export const MESSAGE_HIDE = 'GLOBAL_MESSAGE/HIDE';
export const MESSAGE_REMOVE = 'GLOBAL_MESSAGE/REMOVE';
export const addMessageAction = payload => ({ type: MESSAGE_ADD, payload });
export const hideMessageAction = payload => ({ type: MESSAGE_HIDE, payload });
export const removeMessageAction = payload => ({ type: MESSAGE_REMOVE, payload });
