import {take, call, put, fork} from 'redux-saga/effects';
import {
    fetch, create, modifyPassword,
    fetchList, fetchItem, updateItem
} from '../services/user';
import {watch, through} from './RESTful';
import {message} from 'antd';

function* authorize(username, password, replace) {
    try {
        const user = yield call(fetch, username, password);
        if (user && user.username && user.token) {
            user.authorities = user.authorities ? user.authorities.split(',').reduce((s,a)=>{s[a]=a; return s},{}) : {};
            sessionStorage.setItem('user', JSON.stringify({
                time: Date.now(),
                data: user
            }));
            yield put({type: 'LOGIN_SUCCESS', user});
            replace('/');
        } else {
            throw 'Server is Error: Token is invalid';
        }
    } catch (err) {
        console.error(err);
        message.error(err);
        yield put({type: 'LOGIN_ERROR', err})
    }
}

function* loginFlow() {
    while (true) {
        const {username, password, replace} = yield take('LOGIN_REQUEST');
        if (username && password) {
            yield fork(authorize, username, password, replace);
        }
        yield take(['LOGOUT', 'LOGIN_ERROR']);
        sessionStorage.clear();
        replace('/login');
    }
}

export default function*() {
    yield fork(loginFlow);
    yield fork(through('EDIT_USER', updateItem, '修改'));
    yield fork(watch('CREATE_USER', create, '注册'));
    yield fork(watch('FETCH_USER_LIST', fetchList));
    yield fork(watch('FETCH_USER', fetchItem));
    yield fork(watch('MODIFY_USER_PASSWORD', modifyPassword, '修改密码'));
}


