import jwtDecode from '../../helpers/jwt-decode'
import store from '..';

export default function chatReducer(state = {}, { type, name, status, payload, error, msg, members, user }) {
    if (!state) {
        return {};
    }
    if (type === "PROMISE") {

        return {
            ...state,
            [name]: { status, payload, error },
        };
    }
    if (type === "MSG") {
        const chat = state.chat?.userData.payload.chats.find(i => i._id === msg.chat._id)

        console.log('state', state)
        console.log('mssg', msg)

        const newState = {
            ...state,
            userData: {
                ...state.userData,
                payload: {
                    ...state.userData.payload,
                    chats: state.userData.payload.chats.map(item => {
                        if (item._id === msg.chat._id) {
                            item.messages = [...item.messages, {
                                createdAt: msg.createdAt,
                                media: null,
                                owner: msg.owner,
                                text: msg.text,
                                _id: msg._id
                            }]
                            return item
                        } else return item
                    })

                }

            },
        };

        return newState;
    }
    if (type === "CHAT") {
            if (payload) {
                const oldChats = { ...state };

                for (const chat of payload) {
                    const oldChat = oldChats[chat._id];

                    if (!oldChat) {
                        oldChats[chat._id] = { ...chat };
                    } 
                }
            }
            return state;
    }
    if (type === "ADD_USER_CHAT") {
        const chat = state.chat?.userData.payload.chats
        return {
            ...state,
            // [chat.members]: { members: members + state[] }
        }
    }
    if (type === "CHAT_CLEAR") {
        return {}
    }

    return state;
}