import { combineReducers } from "redux"

// feedReducer - а нужен ли он?
// export function feedReducer(state = {}, { type, status, payload, error, nameOfPromise }) {
//     if (type === 'PROMISE') {
//         return {
//             ...state,
//             [nameOfPromise]: { status, payload, error }
//         }
//     }
// }



// promiseReducer
export function promiseReducer(state = {}, { type, status, payload, error, nameOfPromise }) {
    if (type === 'PROMISE') {
        return {
            ...state,
            [nameOfPromise]: { status, payload, error }
        }
    }
    return state
}





// feedReducer
export function feedReducer(state = {}, { type, status, payload, error, nameOfPromise }) {
    if (type === 'FEED') {
        return {
            ...state,
            [nameOfPromise]: { status, payload, error }
        }
    }
    return state
}





// раскодируем JWT-токен
const jwtDecode = function (token) {
    try {
        let parseData = token.split('.')[1]
        return JSON.parse(atob(parseData))
    }
    catch (e) {
        return undefined
    }
}

// authReducer
export function authReducer(state = {}, { type, token }) {
    if (type === 'AUTH_LOGIN') {

        let payload = jwtDecode(token)

        return state = {
            token,
            payload
        }
    }

    if (type === 'AUTH_LOGOUT') {
        localStorage.clear()
        return {}

    }

    return state
}



// localStoredReducer, который обрабатывает все наши редьюсеры для разных направлений
export function localStoredReducer(originalReducer, localStorageKey) {
    function wrapper(state, action) {
        if (!state) {
            try {
                return JSON.parse(localStorage[localStorageKey])
            }
            catch (error) {

            }
        }
        const newState = originalReducer(state, action)
        localStorage[localStorageKey] = JSON.stringify(newState)

        return newState
    }

    return wrapper
}

// создаем объект с редьюсерами
export const reducers = {
    promise: localStoredReducer(promiseReducer, 'promise'),
    auth: localStoredReducer(authReducer, 'auth'),
    feed: localStoredReducer(feedReducer, 'feed')
}

// скармливаем объект с редьюсерами в combineReducers
export const totalReducer = combineReducers(reducers)

