import {createStore, applyMiddleware, combineReducers} from 'redux';
import thunk from 'redux-thunk';


//----------------------------PromiseReducer---------------------------
export function promiseReducer(state={}, {type,name,status,payload,error}){

    if(type === 'PROMISE'){
        return{
            ...state,
            [name]:{status,payload,error}
        }
    }
    return state
}

const actionPending   = (name) => ({type: 'PROMISE', status: 'PENDING', name})
const actionFulfilled = (name, payload) => ({type: 'PROMISE', status: 'FULFILLED', name, payload})
const actionRejected  = (name, error)   => ({type: 'PROMISE', status: 'REJECTED',  name, error})

export const actionPromise = (name, promise) =>
    async dispatch => {
        dispatch(actionPending(name)) //сигнализируем redux, что промис начался
        try{
            const payload = await promise //ожидаем промиса
            dispatch(actionFulfilled(name, payload)) //сигнализируем redux, что промис успешно выполнен
            return payload //в месте запуска store.dispatch с этим thunk можно так же получить результат промиса
        }
        catch (error){
            dispatch(actionRejected(name, error)) //в случае ошибки - сигнализируем redux, что промис несложился
        }
    }


//--------------------------------jwtDecode---------------------------------
function jwtDecode(token){
    try{
        let payload = JSON.parse(atob(token.split('.')[1]));
        return payload;
    } catch(e){

    }
}

//--------------------------------authReducer-------------------------------------
export function authReducer(state,{type, token}){
    if(state === undefined){
        if(localStorage.authToken){
            type = 'AUTH_LOGIN';
            token = localStorage.authToken
        }
    }

    if(type === 'AUTH_LOGIN'){
        let payload = jwtDecode(token);
        if(payload){
            localStorage.authToken = token;
            return {token,payload}
        }
    }

    if(type === 'AUTH_LOGOUT'){
        localStorage.authToken = '';
        return {};
    }
    return state || {};
}

const actionAuthLogin  = token => ({type: 'AUTH_LOGIN', token})
const actionAuthLogout = ()    => ({type: 'AUTH_LOGOUT'})

const store = createStore(promiseReducer, applyMiddleware(thunk))
store.subscribe(() => console.log(store.getState()))

export default store;

